bitcoin

package module
v0.0.0-...-c4e539a Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2024 License: MIT Imports: 16 Imported by: 0

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/xiaohuasheng0x1/blockchains/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
)
View Source
const SellerSignatureIndex = 2

Variables

This section is empty.

Functions

func AddrToPkScript

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

func CalcFee

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

func CalcTxVirtualSize

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

func ExtractTxFromSignedPSBT

func ExtractTxFromSignedPSBT(psbtHex string) (string, error)

func GenerateAddress

func GenerateAddress(pubKey string, net *chaincfg.Params) (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 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 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 MultiSignBuild

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

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 SignTx

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

Types

type Input

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

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)

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"`
}

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) Build

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

func (*TransactionBuilder) SingleBuild

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

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