// NewAddressWitnessScriptHash returns a new AddressWitnessPubKeyHash.
329762
func NewAddressWitnessScriptHash(witnessProg []byte, net *chaincfg.Params) (*AddressWitnessScriptHash, error) {
	return newAddressWitnessScriptHash(net.Bech32HRPSegwit, witnessProg)
}
1330342
func (vm *Engine) verifyWitnessProgram(witness [][]byte) error {
	if vm.isWitnessVersionActive(0) {
		switch len(vm.witnessProgram) {
		case payToWitnessPubKeyHashDataSize: // P2WKH
			// The witness stack should consist of exactly two
			// items: the signature, and the pubkey.
			if len(witness) != 2 {
				err := fmt.Sprintf("should have exactly two "+
					"items in witness, instead have %v", len(witness))
				return scriptError(ErrWitnessProgramMismatch, err)
			}

			// Now we'll resume execution as if it were a regular
			// p2pkh transaction.
			pkScript, err := payToPubKeyHashScript(vm.witnessProgram)
			if err != nil {
				return err
			}
			pops, err := parseScript(pkScript)
			if err != nil {
				return err
			}

			// Set the stack to the provided witness stack, then
			// append the pkScript generated above as the next
			// script to execute.
			vm.scripts = append(vm.scripts, pops)
			vm.SetStack(witness)

		case payToWitnessScriptHashDataSize: // P2WSH
			// Additionally, The witness stack MUST NOT be empty at
			// this point.
			if len(witness) == 0 {
				return scriptError(ErrWitnessProgramEmpty, "witness "+
					"program empty passed empty witness")
			}

			// Obtain the witness script which should be the last
			// element in the passed stack. The size of the script
			// MUST NOT exceed the max script size.
			witnessScript := witness[len(witness)-1]
			if len(witnessScript) > MaxScriptSize {
				str := fmt.Sprintf("witnessScript size %d "+
					"is larger than max allowed size %d",
					len(witnessScript), MaxScriptSize)
				return scriptError(ErrScriptTooBig, str)
			}

			// Ensure that the serialized pkScript at the end of
			// the witness stack matches the witness program.
			witnessHash := sha256.Sum256(witnessScript)
			if !bytes.Equal(witnessHash[:], vm.witnessProgram) {
				return scriptError(ErrWitnessProgramMismatch,
					"witness program hash mismatch")
			}

			// With all the validity checks passed, parse the
			// script into individual op-codes so w can execute it
			// as the next script.
			pops, err := parseScript(witnessScript)
			if err != nil {
				return err
			}

			// The hash matched successfully, so use the witness as
			// the stack, and set the witnessScript to be the next
			// script executed.
			vm.scripts = append(vm.scripts, pops)
			vm.SetStack(witness[:len(witness)-1])

		default:
			errStr := fmt.Sprintf("length of witness program "+
				"must either be %v or %v bytes, instead is %v bytes",
				payToWitnessPubKeyHashDataSize,
				payToWitnessScriptHashDataSize,
				len(vm.witnessProgram))
			return scriptError(ErrWitnessProgramWrongLength, errStr)
		}
	} else if vm.hasFlag(ScriptVerifyDiscourageUpgradeableWitnessProgram) {
		errStr := fmt.Sprintf("new witness program versions "+
			"invalid: %v", vm.witnessProgram)
		return scriptError(ErrDiscourageUpgradableWitnessProgram, errStr)
	} else {
		// If we encounter an unknown witness program version and we
		// aren't discouraging future unknown witness based soft-forks,
		// then we de-activate the segwit behavior within the VM for
		// the remainder of execution.
		vm.witnessProgram = nil
	}

	if vm.isWitnessVersionActive(0) {
		// All elements within the witness stack must not be greater
		// than the maximum bytes which are allowed to be pushed onto
		// the stack.
		for _, witElement := range vm.GetStack() {
			if len(witElement) > MaxScriptElementSize {
				str := fmt.Sprintf("element size %d exceeds "+
					"max allowed size %d", len(witElement),
					MaxScriptElementSize)
				return scriptError(ErrElementTooBig, str)
			}
		}
	}

	return nil
}
611687
func serializeChainedAddress(branch, index uint32) []byte {
	// The serialized chain address raw data format is:
	//   <branch><index>
	//
	// 4 bytes branch + 4 bytes address index
	rawData := make([]byte, 8)
	binary.LittleEndian.PutUint32(rawData[0:4], branch)
	binary.LittleEndian.PutUint32(rawData[4:8], index)
	return rawData
}
637060
func newManagedAddressWithoutPrivKey(m *ScopedKeyManager,
	derivationPath DerivationPath, pubKey *btcec.PublicKey, compressed bool,
	addrType AddressType) (*managedAddress, error) {

	// Create a pay-to-pubkey-hash address from the public key.
	var pubKeyHash []byte
	if compressed {
		pubKeyHash = btcutil.Hash160(pubKey.SerializeCompressed())
	} else {
		pubKeyHash = btcutil.Hash160(pubKey.SerializeUncompressed())
	}

	var address btcutil.Address
	var err error

	switch addrType {

	case NestedWitnessPubKey:
		// For this address type we'l generate an address which is
		// backwards compatible to Bitcoin nodes running 0.6.0 onwards, but
		// allows us to take advantage of segwit's scripting improvments,
		// and malleability fixes.

		// First, we'll generate a normal p2wkh address from the pubkey hash.
		witAddr, err := btcutil.NewAddressWitnessPubKeyHash(
			pubKeyHash, m.rootManager.chainParams,
		)
		if err != nil {
			return nil, err
		}

		// Next we'll generate the witness program which can be used as a
		// pkScript to pay to this generated address.
		witnessProgram, err := txscript.PayToAddrScript(witAddr)
		if err != nil {
			return nil, err
		}

		// Finally, we'll use the witness program itself as the pre-image
		// to a p2sh address. In order to spend, we first use the
		// witnessProgram as the sigScript, then present the proper
		// <sig, pubkey> pair as the witness.
		address, err = btcutil.NewAddressScriptHash(
			witnessProgram, m.rootManager.chainParams,
		)
		if err != nil {
			return nil, err
		}

	case PubKeyHash:
		address, err = btcutil.NewAddressPubKeyHash(
			pubKeyHash, m.rootManager.chainParams,
		)
		if err != nil {
			return nil, err
		}

	case WitnessPubKey:
		address, err = btcutil.NewAddressWitnessPubKeyHash(
			pubKeyHash, m.rootManager.chainParams,
		)
		if err != nil {
			return nil, err
		}
	}

	return &managedAddress{
		manager:          m,
		address:          address,
		derivationPath:   derivationPath,
		imported:         false,
		internal:         false,
		addrType:         addrType,
		compressed:       compressed,
		pubKey:           pubKey,
		privKeyEncrypted: nil,
		privKeyCT:        nil,
	}, nil
}
403173
func (m *PostgresCreator) NewHashMap(id string) (pinterface.IHashMap, error) {
	return NewHashMap(m.host, id)
}
1066003
func ComputePkScript(sigScript []byte, witness wire.TxWitness) (PkScript, error) {
	var pkScript PkScript

	// Ensure that either an input's signature script or a witness was
	// provided.
	if len(sigScript) == 0 && len(witness) == 0 {
		return pkScript, ErrUnsupportedScriptType
	}

	// We'll start by checking the input's signature script, if provided.
	switch {
	// If a signature script is provided with a length long enough to
	// represent a P2PKH script, then we'll attempt to parse the compressed
	// public key from it.
	case len(sigScript) == pubKeyHashSigScriptLen ||
		len(sigScript) == pubKeyHashSigScriptLen+1:

		// The public key should be found as the last part of the
		// signature script. We'll attempt to parse it to ensure this is
		// a P2PKH redeem script.
		pubKey := sigScript[len(sigScript)-compressedPubKeyLen:]
		if btcec.IsCompressedPubKey(pubKey) {
			pubKeyHash := hash160(pubKey)
			script, err := payToPubKeyHashScript(pubKeyHash)
			if err != nil {
				return pkScript, err
			}

			pkScript.class = PubKeyHashTy
			copy(pkScript.script[:], script)
			return pkScript, nil
		}

		// If it isn't, we'll assume it is a P2SH signature script.
		fallthrough

	// If we failed to parse a compressed public key from the script in the
	// case above, or if the script length is not that of a P2PKH one, and
	// our redeem script is only composed of data pushed, we can assume it's
	// a P2SH signature script.
	case len(sigScript) > 0 && IsPushOnlyScript(sigScript):
		// The redeem script will always be the last data push of the
		// signature script, so we'll parse the script into opcodes to
		// obtain it.
		parsedOpcodes, err := parseScript(sigScript)
		if err != nil {
			return pkScript, err
		}
		redeemScript := parsedOpcodes[len(parsedOpcodes)-1].data

		scriptHash := hash160(redeemScript)
		script, err := payToScriptHashScript(scriptHash)
		if err != nil {
			return pkScript, err
		}

		pkScript.class = ScriptHashTy
		copy(pkScript.script[:], script)
		return pkScript, nil

	case len(sigScript) > 0:
		return pkScript, ErrUnsupportedScriptType
	}

	// If a witness was provided instead, we'll use the last item of the
	// witness stack to determine the proper witness type.
	lastWitnessItem := witness[len(witness)-1]

	switch {
	// If the witness stack has a size of 2 and its last item is a
	// compressed public key, then this is a P2WPKH witness.
	case len(witness) == 2 && len(lastWitnessItem) == compressedPubKeyLen:
		pubKeyHash := hash160(lastWitnessItem)
		script, err := payToWitnessPubKeyHashScript(pubKeyHash)
		if err != nil {
			return pkScript, err
		}

		pkScript.class = WitnessV0PubKeyHashTy
		copy(pkScript.script[:], script)
		return pkScript, nil

	// For any other witnesses, we'll assume it's a P2WSH witness.
	default:
		scriptHash := sha256.Sum256(lastWitnessItem)
		script, err := payToWitnessScriptHashScript(scriptHash[:])
		if err != nil {
			return pkScript, err
		}

		pkScript.class = WitnessV0ScriptHashTy
		copy(pkScript.script[:], script)
		return pkScript, nil
	}
}
1151474
func InsertAddressRow(db *sql.DB, dbA *dbtypes.AddressRow, dupCheck, updateExistingRecords bool) (uint64, error) {
	sqlStmt := internal.MakeAddressRowInsertStatement(dupCheck, updateExistingRecords)
	var id uint64
	err := db.QueryRow(sqlStmt, dbA.Address, dbA.MatchingTxHash, dbA.TxHash,
		dbA.TxVinVoutIndex, dbA.VinVoutDbID, dbA.Value, dbA.TxBlockTime,
		dbA.IsFunding, dbA.ValidMainChain, dbA.TxType).Scan(&id)
	return id, err
}
1216953
func (w *WitnessCache) LookupSha256Witness(hash lntypes.Hash) (lntypes.Preimage, error) {
	witness, err := w.lookupWitness(Sha256HashWitness, hash[:])
	if err != nil {
		return lntypes.Preimage{}, err
	}

	return lntypes.MakePreimage(witness)
}
1102845
func NewPBKDF2SHA256Hasher() *PBKDF2Hasher {
	return &PBKDF2Hasher{
		Algorithm:  "pbkdf2_sha256",
		Iterations: 180000,
		Size:       sha256.Size,
		Digest:     sha256.New,
	}
}
805837
func (c *Client) AddWitnessAddress(address string) (btcutil.Address, error) {
	return c.AddWitnessAddressAsync(address).Receive()
}
498323
func NewHashMap(host *Host, name string) (*HashMap, error) {
	h := &HashMap{host, pq.QuoteIdentifier(name)}
	// Using three columns: element id, key and value
	query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (%s %s, attr hstore)", h.table, ownerCol, defaultStringType)
	if _, err := h.host.db.Exec(query); err != nil {
		if !strings.HasSuffix(err.Error(), "already exists") {
			return nil, err
		}
	}
	if Verbose {
		log.Println("Created HSTORE table " + h.table + " in database " + host.dbname)
	}
	return h, nil
}
1770
func (m *mockWalletController) NewAddress(addrType lnwallet.AddressType,
	change bool) (btcutil.Address, error) {
	addr, _ := btcutil.NewAddressPubKey(
		m.rootKey.PubKey().SerializeCompressed(), &chaincfg.MainNetParams)
	return addr, nil
}
896872
func NewHashPair(pos int, line int) *HashPair {
	return &HashPair{
		NodeType: NodeHashPair,
		Loc:      Loc{pos, line},
	}
}
874375
func newScriptAddress(s *Store, script []byte, bs *BlockStamp) (addr *scriptAddress, err error) {
	class, addresses, reqSigs, err :=
		txscript.ExtractPkScriptAddrs(script, s.netParams())
	if err != nil {
		return nil, err
	}

	scriptHash := btcutil.Hash160(script)

	address, err := btcutil.NewAddressScriptHashFromHash(scriptHash, s.netParams())
	if err != nil {
		return nil, err
	}

	addr = &scriptAddress{
		store:     s,
		address:   address,
		addresses: addresses,
		class:     class,
		reqSigs:   reqSigs,
		flags: scriptFlags{
			hasScript: true,
			change:    false,
		},
		script:     script,
		firstSeen:  time.Now().Unix(),
		firstBlock: bs.Height,
	}

	return addr, nil
}
795830
func encodeAddress(hash160 []byte, netID byte) string {
	// Format is 1 byte for a network and address class (i.e. P2PKH vs
	// P2SH), 20 bytes for a RIPEMD160 hash, and 4 bytes of checksum.
	return base58.CheckEncode(hash160[:ripemd160.Size], netID)
}
66234
func (t *Tx) WitnessHash() *chainhash.Hash {
	// Return the cached hash if it has already been generated.
	if t.txHashWitness != nil {
		return t.txHashWitness
	}

	// Cache the hash and return it.
	hash := t.msgTx.WitnessHash()
	t.txHashWitness = &hash
	return &hash
}
1195096
func (s *Server) WithInsecureAddress(addr string) *Server {
	s.insecureAddr = addr
	return s
}