bitcoin

package module
v0.0.0-...-61460eb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 12, 2024 License: MIT Imports: 27 Imported by: 1

README

bitcoin-sdk

Bitcoin SDK is used to interact with the Bitcoin Mainnet or Testnet, it contains various functions can be used to web3 wallet. The SDK not only support Bitcoin, it also supports following chains:

  • BTC
  • BSV
  • DOGE
  • LTC
  • TBTC

Installation

go get

To obtain the latest version, simply require the project using :

go get -u github.com/okx/go-wallet-sdk/coins/bitcoin

Usage

Supported Functions
// PubKeyToAddr
// GetAddressByPublicKey
// GenerateAddress
// SignTx
// // pbst
// GenerateSignedListingPSBTBase64
New Address
	// address
	network := &chaincfg.TestNet3Params
	pubKeyHex := "0357bbb2d4a9cb8a2357633f201b9c518c2795ded682b7913c6beef3fe23bd6d2f"
	publicKey, err := hex.DecodeString(pubKeyHex)
	p2pkh, err := bitcoin.PubKeyToAddr(publicKey, bitcoin.LEGACY, network)
	if err != nil {
		// todo
		fmt.Println(err)
	}
	fmt.Println(p2pkh)
Transfer
	// transfer btc
	txBuild := bitcoin.NewTxBuild(1, &chaincfg.TestNet3Params)
	txBuild.AddInput("0b2c23f5c2e6326c90cfa1d3925b0d83f4b08035ca6af8fd8f606385dfbc5822", 1, "", "", "", 0)
	txBuild.AddOutput("mvNnCR7EJS4aUReLEw2sL2ZtTZh8CAP8Gp", 53000)
	txBuild.AddOutput("mvNnCR7EJS4aUReLEw2sL2ZtTZh8CAP8Gp", 10000)
	pubKeyMap := make(map[int]string)
	pubKeyMap[0] = "022bc0ca1d6aea1c1e523bfcb33f46131bd1a3240aa04f71c34b1a177cfd5ff933"
	txHex, hashes, err := txBuild.UnSignedTx(pubKeyMap)
	signatureMap := make(map[int]string)
	for i, h := range hashes {
		privateBytes, _ := hex.DecodeString("1790962db820729606cd7b255ace1ac5ebb129ac8e9b2d8534d022194ab25b37")
		prvKey, _ := btcec.PrivKeyFromBytes(privateBytes)
		sign := ecdsa.Sign(prvKey, util.RemoveZeroHex(h))
		signatureMap[i] = hex.EncodeToString(sign.Serialize())
	}
	txHex, err = bitcoin.SignTx(txHex, pubKeyMap, signatureMap)
	if err != nil {
		// todo
		fmt.Println(err)
	}
	fmt.Println(txHex)
PSBT
	// psbt
	var inputs []*bitcoin.TxInput
	inputs = append(inputs, &bitcoin.TxInput{
		TxId:              "46e3ce050474e6da80760a2a0b062836ff13e2a42962dc1c9b17b8f962444206",
		VOut:              uint32(0),
		Sequence:          1,
		Amount:            int64(546),
		Address:           "2NF33rckfiQTiE5Guk5ufUdwms8PgmtnEdc",
		PrivateKey:        "cPnvkvUYyHcSSS26iD1dkrJdV7k1RoUqJLhn3CYxpo398PdLVE22",
		MasterFingerprint: 0xF23F9FD2,
		DerivationPath:    "m/44'/0'/0'/0/0",
		PublicKey:         "0357bbb2d4a9cb8a2357633f201b9c518c2795ded682b7913c6beef3fe23bd6d2f",
	})

	var outputs []*bitcoin.TxOutput
	outputs = append(outputs, &bitcoin.TxOutput{
		Address: "2NF33rckfiQTiE5Guk5ufUdwms8PgmtnEdc",
		Amount:  int64(100000),
	})
	psbtHex, err := bitcoin.GenerateUnsignedPSBTHex(inputs, outputs, network)
	if err != nil {
		// todo
		fmt.Println(err)
	}
	fmt.Println(psbtHex)

License

Most packages or folder are MIT licensed, see package or folder for the respective license.

Documentation

Index

Constants

View Source
const (
	LEGACY        = "legacy"
	SEGWIT_NATIVE = "segwit_native"
	SEGWIT_NESTED = "segwit_nested"
	TAPROOT       = "taproot"
)
View Source
const (
	DefaultTxVersion      = 2
	DefaultSequenceNum    = 0xfffffffd
	DefaultRevealOutValue = int64(546)
	DefaultMinChangeValue = int64(546)

	MaxStandardTxWeight = 4000000 / 10
	WitnessScaleFactor  = 4

	OrdPrefix = "ord"
)
View Source
const (
	ScriptSigPrefix     = "0020"
	Bip0322Tag          = "BIP0322-signed-message"
	Bip0322Opt          = "bip0322-simple"
	SignedMessagePrefix = "Bitcoin Signed Message:\n"
)
View Source
const PART_LEN = 31
View Source
const SellerSignatureIndex = 2

Variables

This section is empty.

Functions

func AddrToPkScript

func AddrToPkScript(addr string, network *chaincfg.Params) ([]byte, error)

func Bip0322Hash

func Bip0322Hash(message string) string

func BtcEncodeBip322

func BtcEncodeBip322(w io.Writer, pver uint32, enc wire.MessageEncoding, msg *wire.MsgTx) error

func BuildToSpend

func BuildToSpend(message string, address string, network *chaincfg.Params) (string, error)

func CalcFee

func CalcFee(ins []*TxInput, outs []*TxOutput, sellerPsbt string, feeRate int64, network *chaincfg.Params) (int64, error)

func CalcFeeForBatchBuy

func CalcFeeForBatchBuy(ins []*TxInput, outs []*TxOutput, sellerPSBTList []string, feeRate int64, network *chaincfg.Params) (int64, error)

func CalcFeeForBatchBuyWithMPC

func CalcFeeForBatchBuyWithMPC(ins []*TxInput, outs []*TxOutput, sellerPSBTList []string, feeRate int64, network *chaincfg.Params, ops ...string) (int64, error)

func CalcInputSigHashForUnsignedPSBT

func CalcInputSigHashForUnsignedPSBT(updater *psbt.Updater, i int, packet *psbt.Packet, prevOutFetcher *txscript.MultiPrevOutFetcher, hashType txscript.SigHashType, publicKey string) (string, error)

func CalcTxVirtualSize

func CalcTxVirtualSize(inputs []*TxInput, outputs []*TxOutput, changeAddress string, minChangeValue int64, network *chaincfg.Params) (int64, error)

func CheckDuplicateOfUpdater

func CheckDuplicateOfUpdater(updater *psbt.Updater, index int)

func ExtractTxFromSignedPSBT

func ExtractTxFromSignedPSBT(psbtHex string) (string, error)

func ExtractTxFromSignedPSBTBIP322

func ExtractTxFromSignedPSBTBIP322(psbtHex string) (string, error)

func GenerateAddress

func GenerateAddress(pubKey string, net *chaincfg.Params) (string, error)

func GenerateBatchBuyingTx

func GenerateBatchBuyingTx(ins []*TxInput, outs []*TxOutput, sellerPSBTList []string, network *chaincfg.Params) (string, error)

func GenerateBatchBuyingTxPsbt

func GenerateBatchBuyingTxPsbt(ins []*TxInput, outs []*TxOutput, sellerPSBTList []string, network *chaincfg.Params) (string, string, error)

func GenerateMultiAddress

func GenerateMultiAddress(redeemScript []byte, net *chaincfg.Params) (string, error)

func GenerateSignedBuyingTx

func GenerateSignedBuyingTx(ins []*TxInput, outs []*TxOutput, sellerPsbt string, network *chaincfg.Params) (string, error)

func GenerateSignedListingPSBTBase64

func GenerateSignedListingPSBTBase64(in *TxInput, out *TxOutput, network *chaincfg.Params) (string, error)

func GenerateUnsignedPSBTHex

func GenerateUnsignedPSBTHex(ins []*TxInput, outs []*TxOutput, network *chaincfg.Params) (string, error)

func GetPsbtFromString

func GetPsbtFromString(psbtStr string) (*psbt.Packet, error)

func GetRandomHash

func GetRandomHash() (string, error)

func GetRedeemScript

func GetRedeemScript(pubKeys []string, minSignNum int) ([]byte, error)

func GetTransactionWeight

func GetTransactionWeight(tx *btcutil.Tx) int64

GetTransactionWeight computes the value of the weight metric for a given transaction. Currently the weight metric is simply the sum of the transactions's serialized size without any witness data scaled proportionally by the WitnessScaleFactor, and the transaction's serialized size including any witness data.

func GetTxHex

func GetTxHex(tx *wire.MsgTx) (string, error)

func GetTxHexBIP322

func GetTxHexBIP322(tx *wire.MsgTx) (string, error)

func GetTxVirtualSize

func GetTxVirtualSize(tx *btcutil.Tx) int64

GetTxVirtualSize computes the virtual size of a given transaction. A transaction's virtual size is based off its weight, creating a discount for any witness data it contains, proportional to the current blockchain.WitnessScaleFactor value.

func IsHexString

func IsHexString(s string) bool

func MPCSignedMessage

func MPCSignedMessage(signature string, publicKeyHex string, network *chaincfg.Params) (string, error)

func MPCSignedMessageCompat

func MPCSignedMessageCompat(message string, signature string, publicKeyHex string, network *chaincfg.Params) (string, error)

func MPCUnsignedMessage

func MPCUnsignedMessage(message string) string

func MultiSignBuild

func MultiSignBuild(tx *wire.MsgTx, priKeyList []string) (string, error)

func NewPsbt

func NewPsbt(inputs []*wire.OutPoint,
	outputs []*wire.TxOut, version int32, nLockTime uint32,
	nSequences []uint32, opts ...string) (*psbt.Packet, error)

NewPsbt compatible for bip0322

func NewTxFromHex

func NewTxFromHex(txHex string) (*wire.MsgTx, error)

NewTxFromHex Second signature

func PayToPubKeyHashScript

func PayToPubKeyHashScript(pubKeyHash []byte) ([]byte, error)

func PayToWitnessPubKeyHashScript

func PayToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, error)

func PubKeyToAddr

func PubKeyToAddr(publicKey []byte, addrType string, network *chaincfg.Params) (string, error)

func Sign

func Sign(tx *wire.MsgTx, privateKeys []*btcec.PrivateKey, prevOutFetcher *txscript.MultiPrevOutFetcher) error

func SignBip0322

func SignBip0322(message string, address string, privateKey string) (string, error)

func SignMessage

func SignMessage(wif string, message string) (string, error)

func SignPsbtWithKeyPathAndScriptPath

func SignPsbtWithKeyPathAndScriptPath(psbtHex string, privKey string, network *chaincfg.Params, option *SignPsbtOption) (string, error)

func SignRawPSBTTransaction

func SignRawPSBTTransaction(psbtHex string, privKey string) (string, error)

func SignTx

func SignTx(raw string, pubKeyMap map[int]string, signatureMap map[int]string) (string, error)

func VerifyMessage

func VerifyMessage(signatureStr, message, publicKeyHex, signType string) (bool, error)

Types

type GenerateMPCPSbtTxRes

type GenerateMPCPSbtTxRes struct {
	Psbt         string   `json:"psbt"`
	PsbtTx       string   `json:"psbtTx"`
	SignHashList []string `json:"signHashList"`
}

func GenerateMPCSignedBuyingTx

func GenerateMPCSignedBuyingTx(psbtBase64 string, signatures []string, pubKey string, batchSize int) (*GenerateMPCPSbtTxRes, error)

func GenerateMPCSignedListingPSBT

func GenerateMPCSignedListingPSBT(psbtBase64 string, signature string, pubKey string) (*GenerateMPCPSbtTxRes, error)

func GenerateMPCSignedPSBT

func GenerateMPCSignedPSBT(psbtStr string, pubKeyHex string, signatureList []string) (*GenerateMPCPSbtTxRes, error)

func GenerateMPCUnsignedBuyingPSBT

func GenerateMPCUnsignedBuyingPSBT(ins []*TxInput, outs []*TxOutput, sellerPSBTList []string, network *chaincfg.Params) (*GenerateMPCPSbtTxRes, error)

func GenerateMPCUnsignedListingPSBT

func GenerateMPCUnsignedListingPSBT(in *TxInput, out *TxOutput, network *chaincfg.Params) (*GenerateMPCPSbtTxRes, error)

func GenerateMPCUnsignedPSBT

func GenerateMPCUnsignedPSBT(psbtStr string, pubKeyHex string) (*GenerateMPCPSbtTxRes, error)

func MPCSignedBip0322

func MPCSignedBip0322(message string, address string, publicKey string, signatureList []string, network *chaincfg.Params) (*GenerateMPCPSbtTxRes, error)

func MPCUnsignedBip0322

func MPCUnsignedBip0322(message string, address string, publicKey string, network *chaincfg.Params) (*GenerateMPCPSbtTxRes, error)

type Input

type Input struct {
	// contains filtered or unexported fields
}

type InscribeForMPCRes

type InscribeForMPCRes struct {
	SigHashList  []string `json:"sigHashList"`
	CommitTx     string   `json:"commitTx"`
	RevealTxs    []string `json:"revealTxs"`
	CommitTxFee  int64    `json:"commitTxFee"`
	RevealTxFees []int64  `json:"revealTxFees"`
	CommitAddrs  []string `json:"commitAddrs"`
}

func InscribeForMPCSigned

func InscribeForMPCSigned(request *InscriptionRequest, network *chaincfg.Params, commitTx string, signatures []string) (*InscribeForMPCRes, error)

func InscribeForMPCUnsigned

func InscribeForMPCUnsigned(request *InscriptionRequest, network *chaincfg.Params, unsignedCommitHash, signedCommitTxHash *chainhash.Hash) (*InscribeForMPCRes, error)

type InscribeTxs

type InscribeTxs struct {
	CommitTx     string   `json:"commitTx"`
	RevealTxs    []string `json:"revealTxs"`
	CommitTxFee  int64    `json:"commitTxFee"`
	RevealTxFees []int64  `json:"revealTxFees"`
	CommitAddrs  []string `json:"commitAddrs"`
}

func Inscribe

func Inscribe(network *chaincfg.Params, request *InscriptionRequest) (*InscribeTxs, error)

func Src20Inscribe

func Src20Inscribe(network *chaincfg.Params, request *Src20InscriptionRequest) (*InscribeTxs, error)

type InscriptionBuilder

type InscriptionBuilder struct {
	Network                   *chaincfg.Params
	CommitTxPrevOutputFetcher *txscript.MultiPrevOutFetcher
	CommitTxPrivateKeyList    []*btcec.PrivateKey
	InscriptionTxCtxDataList  []*inscriptionTxCtxData
	RevealTxPrevOutputFetcher *txscript.MultiPrevOutFetcher
	CommitTxPrevOutputList    []*PrevOutput
	RevealTx                  []*wire.MsgTx
	CommitTx                  *wire.MsgTx
	MustCommitTxFee           int64
	MustRevealTxFees          []int64
	CommitAddrs               []string
}

func NewInscriptionTool

func NewInscriptionTool(network *chaincfg.Params, request *InscriptionRequest) (*InscriptionBuilder, error)

func (*InscriptionBuilder) CalculateFee

func (builder *InscriptionBuilder) CalculateFee() (int64, []int64)

func (*InscriptionBuilder) GetCommitTxHex

func (builder *InscriptionBuilder) GetCommitTxHex() (string, error)

func (*InscriptionBuilder) GetRevealTxHexList

func (builder *InscriptionBuilder) GetRevealTxHexList() ([]string, error)

type InscriptionData

type InscriptionData struct {
	ContentType string `json:"contentType"`
	Body        []byte `json:"body"`
	RevealAddr  string `json:"revealAddr"`
}

type InscriptionRequest

type InscriptionRequest struct {
	CommitTxPrevOutputList []*PrevOutput     `json:"commitTxPrevOutputList"`
	CommitFeeRate          int64             `json:"commitFeeRate"`
	RevealFeeRate          int64             `json:"revealFeeRate"`
	InscriptionDataList    []InscriptionData `json:"inscriptionDataList"`
	RevealOutValue         int64             `json:"revealOutValue"`
	ChangeAddress          string            `json:"changeAddress"`
	MinChangeValue         int64             `json:"minChangeValue"`
}

type Output

type Output struct {
	// contains filtered or unexported fields
}

type PrevOutput

type PrevOutput struct {
	TxId       string `json:"txId"`
	VOut       uint32 `json:"vOut"`
	Amount     int64  `json:"amount"`
	Address    string `json:"address"`
	PrivateKey string `json:"privateKey"`
	PublicKey  string `json:"publicKey"`
}

type SignPsbtOption

type SignPsbtOption struct {
	AutoFinalized bool           `json:"autoFinalized"`
	ToSignInputs  []*ToSignInput `json:"toSignInputs"`
}

type Src20InscriptionRequest

type Src20InscriptionRequest struct {
	CommitTxPrevOutputList []*PrevOutput    `json:"commitTxPrevOutputList"`
	CommitFeeRate          int64            `json:"commitFeeRate"`
	InscriptionData        *InscriptionData `json:"inscriptionDataList"`
	RevealOutValue         int64            `json:"revealOutValue"`
	Address                string           `json:"address"`
	DustSize               int64            `json:"dustSize"`
}

type Src20InscriptionTool

type Src20InscriptionTool struct {
	Network                   *chaincfg.Params
	CommitTxPrevOutputFetcher *txscript.MultiPrevOutFetcher
	CommitTxPrivateKeyList    []*btcec.PrivateKey
	RevealTxPrevOutputFetcher *txscript.MultiPrevOutFetcher
	CommitTxPrevOutputList    []*PrevOutput
	CommitTx                  *wire.MsgTx
	MustCommitTxFee           int64
	CommitAddrs               []string
}

func NewSrc20InscriptionTool

func NewSrc20InscriptionTool(network *chaincfg.Params, request *Src20InscriptionRequest) (*Src20InscriptionTool, error)

func (*Src20InscriptionTool) CalculateFee

func (tool *Src20InscriptionTool) CalculateFee() (int64, []int64)

func (*Src20InscriptionTool) GetCommitTxHex

func (tool *Src20InscriptionTool) GetCommitTxHex() (string, error)

type ToSignInput

type ToSignInput struct {
	Index              int    `json:"index"`
	Address            string `json:"address"`
	PublicKey          string `json:"publicKey"`
	SigHashTypes       []int  `json:"sighashTypes"`
	DisableTweakSigner bool   `json:"disableTweakSigner"`
}

type TransactionBuilder

type TransactionBuilder struct {
	// contains filtered or unexported fields
}

func NewTxBuild

func NewTxBuild(version int32, netParams *chaincfg.Params) *TransactionBuilder

func (*TransactionBuilder) AddInput

func (build *TransactionBuilder) AddInput(txId string, vOut uint32, privateKeyHex string,
	redeemScript string, address string, amount int64)

func (*TransactionBuilder) AddInput2

func (build *TransactionBuilder) AddInput2(txId string, vOut uint32, privateKey string, address string, amount int64)

func (*TransactionBuilder) AddOutput

func (build *TransactionBuilder) AddOutput(address string, amount int64)

func (*TransactionBuilder) AddOutput2

func (build *TransactionBuilder) AddOutput2(address string, script string, amount int64)

func (*TransactionBuilder) AppendInput

func (build *TransactionBuilder) AppendInput(input Input)

func (*TransactionBuilder) AppendOutput

func (build *TransactionBuilder) AppendOutput(o Output)

func (*TransactionBuilder) Build

func (build *TransactionBuilder) Build() (*wire.MsgTx, error)

func (*TransactionBuilder) SingleBuild

func (build *TransactionBuilder) SingleBuild() (string, error)

func (*TransactionBuilder) TotalInputAmount

func (t *TransactionBuilder) TotalInputAmount() int64

func (*TransactionBuilder) TotalOutputAmount

func (t *TransactionBuilder) TotalOutputAmount() int64

func (*TransactionBuilder) UnSignedTx

func (build *TransactionBuilder) UnSignedTx(pubKeyMap map[int]string) (string, map[int]string, error)

type TxInput

type TxInput struct {
	TxId              string
	VOut              uint32
	Sequence          uint32
	Amount            int64
	Address           string
	PrivateKey        string
	NonWitnessUtxo    string
	MasterFingerprint uint32
	DerivationPath    string
	PublicKey         string
}

type TxOutput

type TxOutput struct {
	Address           string
	Amount            int64
	IsChange          bool
	MasterFingerprint uint32
	DerivationPath    string
	PublicKey         string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL