// PgNodeTreeSend calls the stored procedure 'pg_catalog.pg_node_tree_send(pg_node_tree) bytea' on db.
492470
func PgNodeTreeSend(db XODB, v0 pgtypes.PgNodeTree) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.pg_node_tree_send($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
1012341
func parseEmbed(t *Tree, start Pos) (Node, error) {
	expr, with, only, err := parseIncludeOrEmbed(t)
	if err != nil {
		return nil, err
	}
	t.pushBlockStack()
	for {
		tok := t.nextNonSpace()
		if tok.tokenType == tokenEOF {
			return nil, newUnclosedTagError("embed", start)
		} else if tok.tokenType == tokenTagOpen {
			tok, err := t.expect(tokenName)
			if err != nil {
				return nil, err
			}
			if tok.value == "endembed" {
				t.next()
				_, err := t.expect(tokenTagClose)
				if err != nil {
					return nil, err
				}
				break
			} else if tok.value == "block" {
				n, err := parseBlock(t, start)
				if err != nil {
					return nil, err
				}
				if _, ok := n.(*BlockNode); !ok {
					return nil, newUnexpectedTokenError(tok)
				}
			} else {
				return nil, newUnexpectedValueError(tok, "endembed or block")
			}
		}
	}
	blockRefs := t.popBlockStack()
	return NewEmbedNode(expr, with, only, blockRefs, start), nil
}
842871
func nodeFromBytes(t *Tr, data []byte) (*Node, error) {
	n := &Node{}
	_, err := n.UnmarshalMsg(data)
	if err != nil {
		panic(err)
		return nil, err
	}

	return n, nil
}
217500
func (pgb *ChainDB) storeBlockTxnTree(msgBlock *MsgBlockPG, txTree int8,
	chainParams *chaincfg.Params, isValid, isMainchain bool,
	updateExistingRecords, updateAddressesSpendingInfo,
	updateTicketsSpendingInfo bool) storeTxnsResult {
	// For the given block and transaction tree, extract the transactions, vins,
	// and vouts.
	dbTransactions, dbTxVouts, dbTxVins := dbtypes.ExtractBlockTransactions(
		msgBlock.MsgBlock, txTree, chainParams, isValid, isMainchain)

	// Store the transactions, vins, and vouts. This sets the VoutDbIds,
	// VinDbIds, and Vouts fields of each Tx in the dbTransactions slice.
	dbAddressRows, txDbIDs, totalAddressRows, numOuts, numIns, err :=
		pgb.storeTxns(dbTransactions, dbTxVouts, dbTxVins, updateExistingRecords)
	if err != nil {
		return storeTxnsResult{err: err}
	}

	// The return value, containing counts of inserted vins/vouts/txns, and an
	// error value.
	txRes := storeTxnsResult{
		numVins:  int64(numIns),
		numVouts: int64(numOuts),
		txDbIDs:  txDbIDs,
	}

	// Flatten the address rows into a single slice, and update the utxoCache.
	var dbAddressRowsFlat []*dbtypes.AddressRow
	var wg sync.WaitGroup
	processAddressRows := func() {
		dbAddressRowsFlat = pgb.flattenAddressRows(dbAddressRows, dbTransactions,
			isMainchain && isValid)
		wg.Done()
	}
	// Do this in parallel with stake tree tree data insertion.
	wg.Add(1)
	go processAddressRows()

	// For a side chain block, set Validators to an empty slice so that there
	// will be no misses even if there are less than 5 votes. Any Validators
	// that do not match a spent ticket hash in InsertVotes are considered
	// misses. By listing no required validators, there are no misses. For side
	// chain blocks, this is acceptable and necessary because the misses table
	// does not record the block hash or main/side chain status.
	if !isMainchain {
		msgBlock.Validators = []string{}
	}

	// If processing stake tree transactions, insert tickets, votes, and misses.
	// Also update pool status and spending information in tickets table
	// pertaining to the new votes, revokes, misses, and expires.
	if txTree == wire.TxTreeStake {
		// Tickets: Insert new (unspent) tickets
		newTicketDbIDs, newTicketTx, err := InsertTickets(pgb.db, dbTransactions, txDbIDs,
			pgb.dupChecks, updateExistingRecords)
		if err != nil && err != sql.ErrNoRows {
			log.Error("InsertTickets:", err)
			txRes.err = err
			return txRes
		}

		// Cache the unspent ticket DB row IDs and and their hashes. Needed do
		// efficiently update their spend status later.
		var unspentTicketCache *TicketTxnIDGetter
		if updateTicketsSpendingInfo {
			for it, tdbid := range newTicketDbIDs {
				pgb.unspentTicketCache.Set(newTicketTx[it].TxID, tdbid)
			}
			unspentTicketCache = pgb.unspentTicketCache
		}

		// Votes: insert votes and misses (tickets that did not vote when
		// called). Return the ticket hash of all misses, which may include
		// revokes at this point. Unrevoked misses are identified when updating
		// ticket spend info below.

		// voteDbIDs, voteTxns, spentTicketHashes, ticketDbIDs, missDbIDs, err := ...
		var missesHashIDs map[string]uint64
		_, _, _, _, missesHashIDs, err = InsertVotes(pgb.db, dbTransactions, txDbIDs,
			unspentTicketCache, msgBlock, pgb.dupChecks, updateExistingRecords,
			pgb.chainParams, pgb.ChainInfo())
		if err != nil && err != sql.ErrNoRows {
			log.Error("InsertVotes:", err)
			txRes.err = err
			return txRes
		}

		if updateTicketsSpendingInfo {
			// Get information for transactions spending tickets (votes and
			// revokes), and the ticket DB row IDs themselves. Also return
			// tickets table row IDs for newly spent tickets, if we are updating
			// them as we go (SetSpendingForTickets). CollectTicketSpendDBInfo
			// uses ChainDB's ticket DB row ID cache (unspentTicketCache), and
			// immediately expires any found entries for a main chain block.
			spendingTxDbIDs, spendTypes, spentTicketHashes, ticketDbIDs, err :=
				pgb.CollectTicketSpendDBInfo(dbTransactions, txDbIDs,
					msgBlock.MsgBlock, isMainchain)
			if err != nil {
				log.Error("CollectTicketSpendDBInfo:", err)
				txRes.err = err
				return txRes
			}

			// Get a consistent view of the stake node at its present height.
			pgb.stakeDB.LockStakeNode()

			// Classify and record the height of each ticket spend (vote or
			// revoke). For revokes, further distinguish miss or expire.
			revokes := make(map[string]uint64)
			blockHeights := make([]int64, len(spentTicketHashes))
			poolStatuses := make([]dbtypes.TicketPoolStatus, len(spentTicketHashes))
			for iv := range spentTicketHashes {
				blockHeights[iv] = int64(msgBlock.Header.Height) /* voteDbTxns[iv].BlockHeight */

				// Vote or revoke
				switch spendTypes[iv] {
				case dbtypes.TicketVoted:
					poolStatuses[iv] = dbtypes.PoolStatusVoted
				case dbtypes.TicketRevoked:
					revokes[spentTicketHashes[iv]] = ticketDbIDs[iv]
					// Revoke reason
					h, err0 := chainhash.NewHashFromStr(spentTicketHashes[iv])
					if err0 != nil {
						log.Errorf("Invalid hash %v", spentTicketHashes[iv])
						continue // no info about spent ticket!
					}
					expired := pgb.stakeDB.BestNode.ExistsExpiredTicket(*h)
					if !expired {
						poolStatuses[iv] = dbtypes.PoolStatusMissed
					} else {
						poolStatuses[iv] = dbtypes.PoolStatusExpired
					}
				}
			}

			// Update tickets table with spending info.
			_, err = SetSpendingForTickets(pgb.db, ticketDbIDs, spendingTxDbIDs,
				blockHeights, spendTypes, poolStatuses)
			if err != nil {
				log.Error("SetSpendingForTickets:", err)
			}

			// Unspent not-live tickets are also either expired or missed.

			// Missed but not revoked
			var unspentMissedTicketHashes []string
			var missStatuses []dbtypes.TicketPoolStatus
			unspentMisses := make(map[string]struct{})
			// missesHashIDs refers to lottery winners that did not vote.
			for miss := range missesHashIDs {
				if _, ok := revokes[miss]; !ok {
					// unrevoked miss
					unspentMissedTicketHashes = append(unspentMissedTicketHashes, miss)
					unspentMisses[miss] = struct{}{}
					missStatuses = append(missStatuses, dbtypes.PoolStatusMissed)
				}
			}

			// Expired but not revoked
			unspentEnM := make([]string, len(unspentMissedTicketHashes))
			// Start with the unspent misses and append unspent expires to get
			// "unspent expired and missed".
			copy(unspentEnM, unspentMissedTicketHashes)
			unspentExpiresAndMisses := pgb.stakeDB.BestNode.MissedByBlock()
			for _, missHash := range unspentExpiresAndMisses {
				// MissedByBlock includes tickets that missed votes or expired
				// (and which may be revoked in this block); we just want the
				// expires, and not the revoked ones. Screen each ticket from
				// MissedByBlock for the actual unspent expires.
				if pgb.stakeDB.BestNode.ExistsExpiredTicket(missHash) {
					emHash := missHash.String()
					// Next check should not be unnecessary. Make sure not in
					// unspent misses from above, and not just revoked.
					_, justMissed := unspentMisses[emHash] // should be redundant
					_, justRevoked := revokes[emHash]      // exclude if revoked
					if !justMissed && !justRevoked {
						unspentEnM = append(unspentEnM, emHash)
						missStatuses = append(missStatuses, dbtypes.PoolStatusExpired)
					}
				}
			}

			// Release the stake node.
			pgb.stakeDB.UnlockStakeNode()

			// Locate the row IDs of the unspent expired and missed tickets. Do
			// not expire the cache entry.
			unspentEnMRowIDs := make([]uint64, len(unspentEnM))
			for iu := range unspentEnM {
				t, err0 := unspentTicketCache.TxnDbID(unspentEnM[iu], false)
				if err0 != nil {
					txRes.err = fmt.Errorf("failed to retrieve ticket %s DB ID: %v",
						unspentEnM[iu], err0)
					return txRes
				}
				unspentEnMRowIDs[iu] = t
			}

			// Update status of the unspent expired and missed tickets.
			numUnrevokedMisses, err := SetPoolStatusForTickets(pgb.db,
				unspentEnMRowIDs, missStatuses)
			if err != nil {
				log.Errorf("SetPoolStatusForTicketsByHash: %v", err)
			} else if numUnrevokedMisses > 0 {
				log.Tracef("Noted %d unrevoked newly-missed tickets.", numUnrevokedMisses)
			}
		} // updateTicketsSpendingInfo
	} // txTree == wire.TxTreeStake

	wg.Wait()

	// Begin a database transaction to insert spending address rows, and (if
	// updateAddressesSpendingInfo) update matching_tx_hash in corresponding
	// funding rows.
	dbTx, err := pgb.db.Begin()
	if err != nil {
		txRes.err = fmt.Errorf(`unable to begin database transaction: %v`, err)
		return txRes
	}

	// Insert each new AddressRow, absent MatchingTxHash (spending txn since
	// these new address rows are *funding*).
	_, err = InsertAddressRowsDbTx(dbTx, dbAddressRowsFlat, pgb.dupChecks, updateExistingRecords)
	if err != nil {
		_ = dbTx.Rollback()
		log.Error("InsertAddressRows:", err)
		txRes.err = err
		return txRes
	}
	txRes.numAddresses = int64(totalAddressRows)
	txRes.addresses = make(map[string]struct{})
	for _, ad := range dbAddressRowsFlat {
		txRes.addresses[ad.Address] = struct{}{}
	}

	for it, tx := range dbTransactions {
		// vins array for this transaction
		txVins := dbTxVins[it]
		for iv := range txVins {
			// Transaction that spends an outpoint paying to >=0 addresses
			vin := &txVins[iv]

			// Skip coinbase inputs (they are new coins and thus have no
			// previous outpoint funding them).
			if bytes.Equal(zeroHashStringBytes, []byte(vin.PrevTxHash)) {
				continue
			}

			// Insert spending txn data in addresses table, and updated spend
			// status for the previous outpoints' rows in the same table.
			vinDbID := tx.VinDbIds[iv]
			spendingTxHash := vin.TxID
			spendingTxIndex := vin.TxIndex
			validMainchain := tx.IsValidBlock && tx.IsMainchainBlock
			// Attempt to retrieve cached data for this now-spent TXO. A
			// successful get will delete the entry from the cache.
			utxoData, ok := pgb.utxoCache.Get(vin.PrevTxHash, vin.PrevTxIndex)
			if !ok {
				log.Tracef("Data for that utxo (%s:%d) wasn't cached!", vin.PrevTxHash, vin.PrevTxIndex)
			}
			numAddressRowsSet, err := insertSpendingAddressRow(dbTx,
				vin.PrevTxHash, vin.PrevTxIndex, int8(vin.PrevTxTree),
				spendingTxHash, spendingTxIndex, vinDbID, utxoData, pgb.dupChecks,
				updateExistingRecords, validMainchain, vin.TxType, updateAddressesSpendingInfo,
				tx.BlockTime)
			if err != nil {
				_ = dbTx.Rollback()
				txRes.err = fmt.Errorf(`insertSpendingAddressRow: %v + %v (rollback)`,
					err, dbTx.Rollback())
				return txRes
			}
			txRes.numAddresses += numAddressRowsSet
		}
	}

	txRes.err = dbTx.Commit()

	return txRes
}
1121585
func (b *Bucket) pageNode(id pgid) (*page, *node) {
	// Inline buckets have a fake page embedded in their value so treat them
	// differently. We'll return the rootNode (if available) or the fake page.
	if b.root == 0 {
		if id != 0 {
			panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
		}
		if b.rootNode != nil {
			return nil, b.rootNode
		}
		return b.page, nil
	}

	// Check the node cache for non-inline buckets.
	if b.nodes != nil {
		if n := b.nodes[id]; n != nil {
			return nil, n
		}
	}

	// Finally lookup the page from the transaction if no node is materialized.
	return b.tx.page(id), nil
}
230432
func UUIDSend(db XODB, v0 pgtypes.UUID) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.uuid_send($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
375762
func (p *FakePeer) RequestNodeData(hashes []common.Hash) error {
	var data [][]byte
	for _, hash := range hashes {
		if entry, err := p.db.Get(hash.Bytes()); err == nil {
			data = append(data, entry)
		}
	}
	p.dl.DeliverNodeData(p.id, data)
	return nil
}
268804
func (p *PushEventCommit) GetTreeID() string {
	if p == nil || p.TreeID == nil {
		return ""
	}
	return *p.TreeID
}
1173201
func NodeFromPb(pb []byte) (Node, error) {
	n := &NodePb{}
	if err := proto.Unmarshal(pb, n); err != nil {
		return nil, err
	}
	return NodeFromNodePb(n), nil
}
688313
func (p *Profiler) SerializeNode(node *numa.Node) fb.UOffsetT {
	cpuList := p.Builder.CreateString(node.CPUList)
	structs.NodeStart(p.Builder)
	structs.NodeAddID(p.Builder, node.ID)
	structs.NodeAddCPUList(p.Builder, cpuList)
	return structs.NodeEnd(p.Builder)
}
170839
func (pc *PCCloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {
	return []v1.NodeAddress{}, cloudprovider.NotImplemented
}
89092
func (t *tree) parseDataRef(tok item) ast.Node {
	var ref = &ast.DataRefNode{tok.pos, tok.val[1:], nil}
	for {
		var accessNode ast.Node
		var nullsafe = 0
		switch tok := t.next(); tok.typ {
		case itemQuestionDotIdent:
			nullsafe = 1
			fallthrough
		case itemDotIdent:
			accessNode = &ast.DataRefKeyNode{tok.pos, nullsafe == 1, tok.val[nullsafe+1:]}
		case itemQuestionDotIndex:
			nullsafe = 1
			fallthrough
		case itemDotIndex:
			index, err := strconv.ParseInt(tok.val[nullsafe+1:], 10, 0)
			if err != nil {
				t.error(err)
			}
			accessNode = &ast.DataRefIndexNode{tok.pos, nullsafe == 1, int(index)}
		case itemQuestionKey:
			nullsafe = 1
			fallthrough
		case itemLeftBracket:
			accessNode = &ast.DataRefExprNode{tok.pos, nullsafe == 1, t.parseExpr(0)}
			t.expect(itemRightBracket, "dataref")
		default:
			t.backup()
			return ref
		}
		ref.Access = append(ref.Access, accessNode)
	}
}
385700
func (nt *NodeTree) AddNode(n *v1.Node) {
	nt.mu.Lock()
	defer nt.mu.Unlock()
	nt.addNode(n)
}
1368729
func DecodeTree(s storer.EncodedObjectStorer, o plumbing.EncodedObject) (*Tree, error) {
	t := &Tree{s: s}
	if err := t.Decode(o); err != nil {
		return nil, err
	}

	return t, nil
}
164954
func (treeNode *TreeNode) Dump() {
	fmt.Printf("%s<%p>%q\n", strings.Repeat(" ", 4*treeNode.Depth), treeNode, treeNode.astNodeDump())
	for _, child := range treeNode.Children {
		child.Dump()
	}
}
634184
func nextNode(it iterator.Iterator) *Node {
	for end := false; !end; end = !it.Next() {
		id, rest := splitNodeKey(it.Key())
		if string(rest) != dbDiscoverRoot {
			continue
		}
		return mustDecodeNode(id[:], it.Value())
	}
	return nil
}
114185
func (db *DB) DeleteNode(id ID) {
	deleteRange(db.lvl, nodeKey(id))
}