outscript

package module
v0.3.25 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 29 Imported by: 0

README

outscript

Go Reference Coverage Status

A Go package for generating output scripts, parsing/encoding addresses, and building/signing transactions across multiple cryptocurrency networks.

Install

go get github.com/KarpelesLab/outscript

Supported Networks

Network Address Formats Transactions
Bitcoin p2pkh, p2pk, p2wpkh, p2sh:p2wpkh, p2wsh, p2tr BtcTx
Bitcoin Cash p2pkh, p2pk (CashAddr) BtcTx
Litecoin p2pkh, p2pk, p2wpkh, p2sh:p2wpkh BtcTx
Dogecoin p2pkh, p2pk BtcTx
Namecoin p2pkh, p2sh BtcTx
Monacoin p2pkh, p2sh, p2wpkh BtcTx
Dash p2pkh, p2sh BtcTx
Electraproto p2pkh, p2sh, p2wpkh BtcTx
EVM (Ethereum, etc.) EIP-55 checksummed EvmTx
Massa AU (user) / AS (smart contract) -
Solana Base58 (32 bytes) SolanaTx

Usage

Address Generation

Generate addresses from a public key:

// Bitcoin (secp256k1)
key := secp256k1.PrivKeyFromBytes(seed)
s := outscript.New(key.PubKey())

addr, _ := s.Address("p2wpkh", "bitcoin")    // bc1q...
addr, _ = s.Address("p2pkh", "litecoin")      // L...
addr, _ = s.Address("eth")                     // 0x...

// Solana / Massa (ed25519)
key := ed25519.NewKeyFromSeed(seed)
s := outscript.New(key.Public())

addr, _ = s.Address("solana", "solana")        // base58
addr, _ = s.Address("massa", "massa")          // AU...
Address Parsing
// Bitcoin-family
out, _ := outscript.ParseBitcoinBasedAddress("bitcoin", "bc1q...")
out, _ = outscript.ParseBitcoinBasedAddress("auto", "1A1zP1...")  // auto-detect network

// EVM
out, _ := outscript.ParseEvmAddress("0x2AeB8ADD...")

// Solana
out, _ := outscript.ParseSolanaAddress("83astBRguLMdt2h5U1Tpdq5tjFoJ...")

// Massa
out, _ := outscript.ParseMassaAddress("AU16f3K8uWS8cSJaXb7...")
Bitcoin Transactions
tx := &outscript.BtcTx{Version: 2}

// Add inputs
tx.In = append(tx.In, &outscript.BtcTxInput{
    TXID:     txid,
    Vout:     0,
    Sequence: 0xffffffff,
})

// Add outputs
tx.AddNetOutput("bitcoin", "bc1q...", 50000)

// Sign (supports p2pkh, p2wpkh, p2sh:p2wpkh, p2wsh, etc.)
tx.Sign(&outscript.BtcTxSign{
    Key:    privKey,
    Scheme: "p2wpkh",
    Amount: 100000, // input value, required for segwit
})

// Serialize
data, _ := tx.MarshalBinary()

// Estimate size for fee calculation
size := tx.ComputeSize()
EVM Transactions
tx := &outscript.EvmTx{
    Type:      outscript.EvmTxEIP1559,
    ChainId:   1,
    Nonce:     0,
    GasTipCap: big.NewInt(1_000_000_000),
    GasFeeCap: big.NewInt(20_000_000_000),
    Gas:       21000,
    To:        "0x...",
    Value:     big.NewInt(1_000_000_000_000_000_000),
    Data:      nil,
}

// Or build contract calls with ABI encoding
tx.Call("transfer(address,uint256)", recipientAddr, amount)

// Sign and serialize
tx.Sign(privKey)
data, _ := tx.MarshalBinary()

// Recover sender from signed transaction
sender, _ := tx.SenderAddress()

Supported EVM transaction types: Legacy, EIP-2930, EIP-1559, EIP-4844.

EVM ABI Encoding

Encode calldata without a full ABI definition:

data, _ := outscript.EvmCall("transfer(address,uint256)", recipientAddr, amount)
data, _ = outscript.EvmCall("approve(address,uint256)", spender, big.NewInt(0))

Or use AbiBuffer directly for more control:

buf := outscript.NewAbiBuffer(nil)
buf.EncodeAbi("balanceOf(address)", addr)
calldata := buf.Call("balanceOf(address)")
Solana Transactions
from := must(outscript.ParseSolanaKey("..."))
to := must(outscript.ParseSolanaKey("..."))
blockhash := must(outscript.ParseSolanaKey("..."))

// Build a transfer instruction
ix := outscript.SolanaTransferInstruction(from, to, 1_000_000) // lamports

// Compile into a transaction (handles account dedup, sorting, and compilation)
tx := outscript.NewSolanaTx(from, blockhash, ix)

// Sign with Ed25519
tx.Sign(privKey)

// Serialize
data, _ := tx.MarshalBinary()

// Transaction ID is the first signature
txid, _ := tx.Hash()
Block Rewards

Calculate block rewards and cumulative supply:

reward, _ := outscript.BlockReward("bitcoin", 840000)      // 3.125 BTC in satoshis
total, _ := outscript.CumulativeReward("bitcoin", 840000)   // total minted through block 840000

Supported: bitcoin, bitcoin-cash, bitcoin-testnet, litecoin, namecoin, monacoin, dogecoin, dash, electraproto.

Output Script Analysis

Identify output script types and extract public key hashes:

out := outscript.GuessOut(scriptBytes, pubKeyHint)
fmt.Println(out.Name) // "p2wpkh", "p2pkh", "p2sh", etc.

// Get all possible output formats for a key
outs := outscript.GetOuts(pubKey)

Architecture

The package is built around composable primitives:

  • Format - A sequence of Insertable operations (literal bytes, lookups, hashes, push-data encoding) that define how to derive an output script from a public key.
  • Script - Holds a public key and generates output scripts by evaluating Format definitions. Results are cached.
  • Out - A generated output script with its format name, hex encoding, and network flags. Can be converted to/from human-readable addresses.
  • Transaction - Interface implemented by BtcTx, EvmTx, and SolanaTx for binary serialization and hashing.

License

See LICENSE file.

Documentation

Overview

Package outscript generates potential output scripts for a given public key.

It supports Bitcoin and Bitcoin-like cryptocurrency output script formats (P2PKH, P2SH, P2WPKH, P2WSH, P2PK, P2TR, etc.), EVM-based networks (Ethereum and compatible chains), and other blockchains such as Litecoin, Dogecoin, Namecoin, Monacoin, Electraproto, Dash, Bitcoin Cash, and Massa.

The package also provides transaction building and signing for both Bitcoin-style (with segwit witness data) and EVM transactions, as well as block reward calculations for various cryptocurrency networks.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Formats maps script format names (e.g. "p2pkh", "p2wpkh", "eth") to their
	// corresponding [Format] definitions.
	Formats = map[string]Format{
		"p2pkh":  Format{Bytes{0x76, 0xa9}, IPushBytes{IHash160(Lookup("pubkey:comp"))}, Bytes{0x88, 0xac}},
		"p2pukh": Format{Bytes{0x76, 0xa9}, IPushBytes{IHash160(Lookup("pubkey:uncomp"))}, Bytes{0x88, 0xac}},
		"p2pk":   Format{IPushBytes{Lookup("pubkey:comp")}, Bytes{0xac}},
		"p2puk":  Format{IPushBytes{Lookup("pubkey:uncomp")}, Bytes{0xac}},
		"p2wpkh": Format{Bytes{0}, IPushBytes{IHash160(Lookup("pubkey:comp"))}},

		"p2sh:p2pkh":  Format{Bytes{0xa9}, IPushBytes{IHash160(Lookup("p2pkh"))}, Bytes{0x87}},
		"p2sh:p2pukh": Format{Bytes{0xa9}, IPushBytes{IHash160(Lookup("p2pukh"))}, Bytes{0x87}},
		"p2sh:p2pk":   Format{Bytes{0xa9}, IPushBytes{IHash160(Lookup("p2pk"))}, Bytes{0x87}},
		"p2sh:p2puk":  Format{Bytes{0xa9}, IPushBytes{IHash160(Lookup("p2puk"))}, Bytes{0x87}},
		"p2sh:p2wpkh": Format{Bytes{0xa9}, IPushBytes{IHash160(Lookup("p2wpkh"))}, Bytes{0x87}},

		"p2wsh:p2pkh":  Format{Bytes{0}, IPushBytes{IHash(Lookup("p2pkh"), sha256.New)}},
		"p2wsh:p2pukh": Format{Bytes{0}, IPushBytes{IHash(Lookup("p2pukh"), sha256.New)}},
		"p2wsh:p2pk":   Format{Bytes{0}, IPushBytes{IHash(Lookup("p2pk"), sha256.New)}},
		"p2wsh:p2puk":  Format{Bytes{0}, IPushBytes{IHash(Lookup("p2puk"), sha256.New)}},
		"p2wsh:p2wpkh": Format{Bytes{0}, IPushBytes{IHash(Lookup("p2wpkh"), sha256.New)}},

		"eth": Format{IHash(Lookup("pubkey:uncomp"), newEtherHash)},

		"massa_pubkey": Format{Bytes{0}, Lookup("pubkey:ed25519")},
		"massa":        Format{Bytes{0, 0}, IHash(Lookup("massa_pubkey"), newMassaHash)},

		"solana": Format{Lookup("pubkey:ed25519")},
	}

	// FormatsPerNetwork is a table listing the typically available formats for each network
	FormatsPerNetwork = map[string][]string{
		"bitcoin":      []string{"p2wpkh", "p2sh:p2wpkh", "p2puk", "p2pk", "p2pukh", "p2pkh"},
		"bitcoin-cash": []string{"p2puk", "p2pk", "p2pukh", "p2pkh"},
		"litecoin":     []string{"p2wpkh", "p2sh:p2wpkh", "p2puk", "p2pk", "p2pukh", "p2pkh"},
		"dogecoin":     []string{"p2puk", "p2pk", "p2pukh", "p2pkh"},
		"evm":          []string{"eth"},
		"massa":        []string{"massa"},
		"solana":       []string{"solana"},
	}
)
View Source
var SolanaSystemProgram = mustParseSolanaKey("11111111111111111111111111111111")

SolanaSystemProgram is the address of the Solana System Program.

Functions

func BlockReward

func BlockReward(network string, blockHeight uint64) (*big.Int, error)

BlockReward returns the block reward at the given blockHeight for the specified network, reading from chainConfigs.

func CumulativeReward

func CumulativeReward(network string, blockHeight uint64) (*big.Int, error)

CumulativeReward returns the total minted coins from block 0 through blockHeight (inclusive) for the specified network.

func EvmCall

func EvmCall(method string, params ...any) ([]byte, error)

EvmCall generates calldata for a given EVM call, performing absolutely no check on the provided parameters as to whether these match the ABI or not.

func GuessPubKeyAndHashByInScript

func GuessPubKeyAndHashByInScript(scriptBytes []byte) (foundPubKey []byte, foundPubKeyHash []byte)

GuessPubKeyAndHashByInScript will attempt to guess the pubkey hash (address component) and possibly the pubkey from an input script.

func GuessPubKeyAndHashByOutScript

func GuessPubKeyAndHashByOutScript(scriptBytes []byte) (foundPubKey []byte, foundPubKeyHash []byte)

GuessPubKeyAndHashByOutScript will attempt to guess the pubkey hash (address component) and possibly the pubkey from a output script.

func ParsePushBytes

func ParsePushBytes(v []byte) ([]byte, int)

ParsePushBytes decodes a Bitcoin script push operation at the start of v, returning the pushed data and the total number of bytes consumed. It returns (nil, 0) on error.

func PushBytes

func PushBytes(v []byte) []byte

PushBytes encodes a byte slice as a Bitcoin script push operation, choosing the appropriate opcode (direct push for <=75 bytes, OP_PUSHDATA1/2/4 for larger data).

Types

type AbiBuffer

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

AbiBuffer is a builder for EVM ABI-encoded data. It supports encoding uint256, address, bytes, and string types, as well as generating method call data with the 4-byte function selector.

func NewAbiBuffer

func NewAbiBuffer(buf []byte) *AbiBuffer

NewAbiBuffer returns a new AbiBuffer initialized with the given byte slice.

func (*AbiBuffer) AppendAddressAny

func (buf *AbiBuffer) AppendAddressAny(v any) error

AppendAddressAny appends a value as an ABI address parameter.

func (*AbiBuffer) AppendBigInt

func (buf *AbiBuffer) AppendBigInt(v *big.Int) error

AppendBigInt appends a big.Int value to the buffer

func (*AbiBuffer) AppendBufferAny

func (buf *AbiBuffer) AppendBufferAny(v any) error

AppendBufferAny appends a value as an ABI bytes/string parameter. Supported Go types are []byte and string.

func (*AbiBuffer) AppendBytes

func (buf *AbiBuffer) AppendBytes(v []byte)

AppendBytes adds a byte buffer as parameter (which will be actually an offset to a later area)

func (*AbiBuffer) AppendUint256Any

func (buf *AbiBuffer) AppendUint256Any(v any) error

AppendUint256Any appends a value as a uint256-style ABI parameter. Supported Go types are bool, int, and *big.Int.

func (*AbiBuffer) Bytes

func (buf *AbiBuffer) Bytes() []byte

Bytes will return the encoded ABI buffer

func (*AbiBuffer) Call

func (buf *AbiBuffer) Call(method string) []byte

Call returns a EVM abi-encoded method call

func (*AbiBuffer) EncodeAbi

func (buf *AbiBuffer) EncodeAbi(abi string, params ...any) error

EncodeAbi takes as first parameter an abi such as "transfer(address,uint256)" and a matching number of parameters.

func (*AbiBuffer) EncodeAuto

func (buf *AbiBuffer) EncodeAuto(params ...any) error

EncodeAuto will encode a bunch of any values into whatever makes sense for the format they are. *big.Int will become uint256, *Script will become addresses, strings and []byte becomes bytes.

Non-compact format is fairly simple since all numeric values are uint256 (including addresses), and only strings/byte arrays are offsets to the end of the buffer where these are stored as length+data+padding

func (*AbiBuffer) EncodeTypes

func (buf *AbiBuffer) EncodeTypes(types []string, params ...any) error

EncodeTypes encodes the given parameters according to the specified ABI type strings. Supported types are "uint", "uint8"..."uint256", "bytes4", "bytes32", "address", "bytes", and "string".

type BtcAmount

type BtcAmount uint64

BtcAmount represents a Bitcoin amount in satoshis (1 BTC = 100,000,000 satoshis). It marshals to JSON as a decimal string with 8 decimal places and supports unmarshaling from decimal strings, integers, and hex-encoded values.

func (BtcAmount) MarshalJSON

func (b BtcAmount) MarshalJSON() ([]byte, error)

MarshalJSON encodes the amount as a JSON number with 8 decimal places (e.g. "1.00000000").

func (*BtcAmount) UnmarshalJSON

func (ba *BtcAmount) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a JSON number or quoted string into a BtcAmount.

func (*BtcAmount) UnmarshalText

func (ba *BtcAmount) UnmarshalText(b []byte) error

UnmarshalText decodes a text representation into a BtcAmount. It accepts decimal strings (e.g. "1.5"), integer strings (e.g. "100000000"), and hex-prefixed strings (e.g. "0x5f5e100").

type BtcTx

type BtcTx struct {
	Version  uint32         `json:"version"`
	In       []*BtcTxInput  `json:"vin"`
	Out      []*BtcTxOutput `json:"vout"`
	Locktime uint32         `json:"locktime"`
}

BtcTx represents a Bitcoin transaction including its inputs, outputs, and witness data.

func (*BtcTx) AddNetOutput

func (tx *BtcTx) AddNetOutput(network, address string, amount uint64) error

AddNetOutput adds the specified address as an output to the transaction. The address will be parsed for the given network and an error will be returned if the address is not valid. Passing "auto" as network name disables all checks and it is up to the caller to confirm the address and resulting output is valid first.

func (*BtcTx) AddOutput

func (tx *BtcTx) AddOutput(address string, amount uint64) error

AddOutput adds the specified address as an output to the transaction. Note that this will not check if the output is valid for a given network, this is up to the caller to confirm things first.

func (*BtcTx) Bytes

func (tx *BtcTx) Bytes() []byte

Bytes returns the serialized transaction, including witness data if present.

func (*BtcTx) ClearInputs

func (tx *BtcTx) ClearInputs()

ClearInputs removes all the input scripts and witnesses from the transaction. Used during signing.

func (*BtcTx) ComputeSize

func (tx *BtcTx) ComputeSize() int

EstimateSize computes the transaction size, taking into account specific rules for segwit.

func (*BtcTx) Dup

func (tx *BtcTx) Dup() *BtcTx

Dup duplicates a transaction and its inputs/outputs

func (*BtcTx) HasWitness

func (tx *BtcTx) HasWitness() bool

HasWitness reports whether any input in the transaction has witness data.

func (*BtcTx) Hash

func (tx *BtcTx) Hash() ([]byte, error)

Hash computes the double SHA-256 transaction hash (txid) in the standard reversed byte order.

func (*BtcTx) MarshalBinary

func (tx *BtcTx) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler and returns the serialized transaction bytes.

func (*BtcTx) ReadFrom

func (tx *BtcTx) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads and parses a Bitcoin transaction from r, including segwit witness data if present.

func (*BtcTx) Sign

func (tx *BtcTx) Sign(keys ...*BtcTxSign) error

Sign will perform signature on the transaction

func (*BtcTx) UnmarshalBinary

func (tx *BtcTx) UnmarshalBinary(buf []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler and parses a serialized transaction.

type BtcTxInput

type BtcTxInput struct {
	TXID      Hex32
	Vout      uint32
	Script    []byte
	Sequence  uint32
	Witnesses [][]byte
}

BtcTxInput represents a single input in a Bitcoin transaction.

func (*BtcTxInput) Bytes

func (in *BtcTxInput) Bytes() []byte

Bytes serializes the input into its binary representation (txid + vout + script + sequence).

func (*BtcTxInput) Dup

func (in *BtcTxInput) Dup() *BtcTxInput

Dup returns a deep copy of the BtcTxInput.

func (*BtcTxInput) MarshalJSON

func (in *BtcTxInput) MarshalJSON() ([]byte, error)

MarshalJSON encodes the transaction input as JSON with hex-encoded script and witness data.

func (*BtcTxInput) Prefill

func (in *BtcTxInput) Prefill(scheme string) error

Prefill will fill the transaction input with empty data matching the expected signature length for the given scheme, if supported

func (*BtcTxInput) ReadFrom

func (in *BtcTxInput) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads and parses a transaction input from r.

type BtcTxOutput

type BtcTxOutput struct {
	Amount BtcAmount
	N      int // not stored
	Script []byte
}

BtcTxOutput represents a single output in a Bitcoin transaction.

func (*BtcTxOutput) Bytes

func (out *BtcTxOutput) Bytes() []byte

Bytes serializes the output into its binary representation (amount + script).

func (*BtcTxOutput) Dup

func (out *BtcTxOutput) Dup() *BtcTxOutput

Dup returns a copy of the BtcTxOutput object; used for transaction signing.

func (*BtcTxOutput) MarshalJSON

func (out *BtcTxOutput) MarshalJSON() ([]byte, error)

MarshalJSON encodes the transaction output as JSON.

func (*BtcTxOutput) ReadFrom

func (out *BtcTxOutput) ReadFrom(r io.Reader) (int64, error)

ReadFrom parses a transaction output from the provided reader.

func (*BtcTxOutput) UnmarshalJSON

func (out *BtcTxOutput) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a JSON representation into a BtcTxOutput.

type BtcTxSign

type BtcTxSign struct {
	Key     crypto.Signer
	Options crypto.SignerOpts
	Scheme  string    // "p2pk", "p2wpkh", "p2wsh:p2pkh", etc
	Amount  BtcAmount // value of input, required for segwit transaction signing
	SigHash uint32
}

BtcTxSign holds the signing parameters for a single transaction input.

type BtcVarInt

type BtcVarInt uint64

BtcVarInt is a Bitcoin variable-length integer as defined in the Bitcoin protocol. Values 0-0xfc are stored as a single byte; larger values use a prefix byte (0xfd, 0xfe, or 0xff) followed by 2, 4, or 8 bytes respectively in little-endian order.

func (BtcVarInt) Bytes

func (v BtcVarInt) Bytes() []byte

Bytes returns the encoded variable-length integer as a byte slice.

func (BtcVarInt) Len

func (v BtcVarInt) Len() int

Len returns the number of bytes needed to encode this variable-length integer.

func (*BtcVarInt) ReadFrom

func (v *BtcVarInt) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads a variable-length integer from r.

func (BtcVarInt) WriteTo

func (v BtcVarInt) WriteTo(w io.Writer) (int64, error)

WriteTo writes the encoded variable-length integer to w.

type Bytes

type Bytes []byte

Bytes is an Insertable that returns a fixed byte sequence.

func (Bytes) Bytes

func (b Bytes) Bytes(*Script) ([]byte, error)

Bytes returns the literal byte sequence.

func (Bytes) String

func (b Bytes) String() string

String returns the hex encoding of the byte sequence.

type EvmTx

type EvmTx struct {
	Nonce      uint64
	GasTipCap  *big.Int // a.k.a. maxPriorityFeePerGas
	GasFeeCap  *big.Int // a.k.a. maxFeePerGas, correspond to GasFee if tx type is legacy or eip2930
	Gas        uint64   // gas of tx, can be obtained with eth_estimateGas, 21000 if Data is empty
	To         string
	Value      *big.Int
	Data       []byte
	ChainId    uint64    // in legacy tx, chainId is encoded in v before signature
	Type       EvmTxType // type of transaction: legacy, eip2930 or eip1559
	AccessList []any     // TODO
	Signed     bool
	Y, R, S    *big.Int
}

EvmTx represents an Ethereum Virtual Machine transaction. It supports legacy, EIP-2930, EIP-1559, and EIP-4844 transaction types, and can be signed, serialized, parsed, and converted to/from JSON.

func (*EvmTx) Call

func (tx *EvmTx) Call(method string, params ...any) error

Call sets the transaction's Data field to the ABI-encoded method call for the given method signature and parameters.

func (*EvmTx) Hash

func (tx *EvmTx) Hash() ([]byte, error)

Hash returns the Keccak-256 hash of the signed transaction's binary encoding.

func (*EvmTx) MarshalBinary

func (tx *EvmTx) MarshalBinary() ([]byte, error)

MarshalBinary transforms the transaction into its binary representation

func (*EvmTx) MarshalJSON

func (tx *EvmTx) MarshalJSON() ([]byte, error)

MarshalJSON encodes the transaction as a JSON object with hex-encoded numeric fields.

func (*EvmTx) ParseTransaction

func (tx *EvmTx) ParseTransaction(buf []byte) error

ParseTransaction will parse an incoming transaction and return an error in case of failure. In case of error, the state of tx is undefined.

func (*EvmTx) RlpFields

func (tx *EvmTx) RlpFields() []any

RlpFields returns the Rlp fields for the given transaction, less the signature fields

func (*EvmTx) SenderAddress

func (tx *EvmTx) SenderAddress() (string, error)

SenderAddress recovers and returns the EIP-55 checksummed sender address from the transaction signature.

func (*EvmTx) SenderPubkey

func (tx *EvmTx) SenderPubkey() (*secp256k1.PublicKey, error)

SenderPubkey recovers the sender's public key from the transaction signature.

func (*EvmTx) Sign

func (tx *EvmTx) Sign(key crypto.Signer) error

Sign signs the transaction using the given key with default signer options.

func (*EvmTx) SignBytes

func (tx *EvmTx) SignBytes() ([]byte, error)

SignBytes returns the bytes used to sign the transaction

func (*EvmTx) SignWithOptions

func (tx *EvmTx) SignWithOptions(key crypto.Signer, opts crypto.SignerOpts) error

SignWithOptions signs the transaction using the given key and signer options.

func (*EvmTx) Signature

func (tx *EvmTx) Signature() (*secp256k1.Signature, error)

Signature returns the parsed secp256k1 signature from the signed transaction.

func (*EvmTx) UnmarshalBinary

func (tx *EvmTx) UnmarshalBinary(buf []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler

func (*EvmTx) UnmarshalJSON

func (tx *EvmTx) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a JSON representation into an EvmTx.

type EvmTxType

type EvmTxType int

EvmTxType represents the type of EVM transaction encoding.

const (
	EvmTxLegacy  EvmTxType = iota // Legacy (pre-EIP-2718) transaction
	EvmTxEIP2930                  // EIP-2930 access list transaction
	EvmTxEIP1559                  // EIP-1559 dynamic fee transaction
	EvmTxEIP4844                  // EIP-4844 blob transaction
)

type Format

type Format []Insertable

Format is a sequence of Insertable values that together define how an output script is constructed from a public key.

type Hex32

type Hex32 [32]byte

Hex32 is a 32-byte array that marshals to and from a hex-encoded JSON string.

func (Hex32) MarshalJSON

func (h Hex32) MarshalJSON() ([]byte, error)

MarshalJSON encodes the 32-byte value as a hex string.

func (Hex32) UnmarshalJSON

func (h Hex32) UnmarshalJSON(v []byte) error

UnmarshalJSON decodes a hex string into the 32-byte value.

type IHashInfo

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

IHashInfo is an Insertable that hashes the output of another Insertable using one or more chained hash functions.

func IHash

func IHash(v Insertable, hash ...func() hash.Hash) IHashInfo

IHash returns an IHashInfo that hashes the output of v using the given hash functions in sequence.

func IHash160

func IHash160(v Insertable) IHashInfo

IHash160 returns an IHashInfo that computes HASH160 (SHA-256 followed by RIPEMD-160) of the output of v.

func (IHashInfo) Bytes

func (i IHashInfo) Bytes(s *Script) ([]byte, error)

Bytes hashes the output of the wrapped Insertable using the configured hash chain.

func (IHashInfo) String

func (i IHashInfo) String() string

String returns a human-readable representation of the hash operation.

type IPushBytes

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

IPushBytes is an Insertable that encodes the output of another Insertable as a Bitcoin script push operation.

func (IPushBytes) Bytes

func (i IPushBytes) Bytes(s *Script) ([]byte, error)

Bytes generates the inner value and wraps it as a Bitcoin script push operation.

func (IPushBytes) String

func (i IPushBytes) String() string

String returns a human-readable representation of the push operation.

type Insertable

type Insertable interface {
	Bytes(*Script) ([]byte, error)
	String() string
}

Insertable is a component that can produce bytes for inclusion in an output script. Implementations include literal Bytes, Lookup references to other formats, IPushBytes for Bitcoin PUSHDATA encoding, and IHashInfo for hashing.

type Lookup

type Lookup string

Lookup is an Insertable that generates bytes by looking up another named format via Script.Generate.

func (Lookup) Bytes

func (l Lookup) Bytes(s *Script) ([]byte, error)

Bytes generates bytes by looking up the named format on the given Script.

func (Lookup) String

func (l Lookup) String() string

String returns the lookup name.

type Out

type Out struct {
	Name   string   `json:"name"`            // p2sh, etc
	Script string   `json:"script"`          // out script
	Flags  []string `json:"flags,omitempty"` // flags
	// contains filtered or unexported fields
}

Out represents a generated output script with its format name, hex-encoded script, and optional flags indicating the target network(s).

func GetOuts

func GetOuts(pubkey crypto.PublicKey) []*Out

GetOuts returns the potential outputs that can be opened in theory with the given pubkey. p2w* values are "pay to segwit" and can only be used on segwit-enabled chains.

func GuessOut

func GuessOut(script []byte, pubkeyhint crypto.PublicKey) *Out

GuessOut will return a out matching the provided script, and attempt to guess the correct type. pubkeyhint can be nil and this function will still be useful, but it won't be able to differenciate between compressed and uncompressed keys if the script contains a hashed key

func ParseBitcoinAddress deprecated

func ParseBitcoinAddress(address string) (*Out, error)

ParseBitcoinAddress parses an address in bitcoin format and returns the matching script, accepting also other networks addresses (in which cash a flag will be set)

Deprecated: use ParseBitcoinBasedAddress instead

func ParseBitcoinBasedAddress

func ParseBitcoinBasedAddress(network, address string) (*Out, error)

ParseBitcoinBasedAddress parses an address in bitcoin format and returns the matching script, for the specified network. The special value "auto" for network will attempt to detect the network.

func ParseEvmAddress

func ParseEvmAddress(address string) (*Out, error)

ParseEvmAddress parses an address to return an Out, supporting EVM-based networks.

func ParseMassaAddress

func ParseMassaAddress(address string) (*Out, error)

ParseMassaAddress parses a Massa network address (starting with "AU" for user accounts or "AS" for smart contracts) and returns the corresponding Out.

func ParseSolanaAddress

func ParseSolanaAddress(address string) (*Out, error)

ParseSolanaAddress parses a Solana base58-encoded address and returns the corresponding Out. A valid Solana address is exactly 32 bytes when decoded.

func (*Out) Address

func (out *Out) Address(flags ...string) (string, error)

Address returns an address matching the provided out. Flags will be used for hints if multiple addresses are possible.

func (*Out) Bytes

func (o *Out) Bytes() []byte

Bytes returns the raw output script bytes.

func (*Out) Hash

func (o *Out) Hash() []byte

Hash will extract the hash part of the Out, or return nil if there is no known hash

func (*Out) String

func (o *Out) String() string

String returns a human-readable representation of the Out in "name:script" format.

type Script

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

Script holds a public key and caches generated output scripts for various formats.

func New

func New(pubkey crypto.PublicKey) *Script

New returns a new Script object for the given public key, which can be used to generate output scripts

func (*Script) Address

func (s *Script) Address(script string, flags ...string) (string, error)

Address formats the key using the specified script (eg. p2sh, etc) and optional flags hints. You can do things like Address("eth") where no hint is needed, or things like Address("p2pkh", "litecoin") so the appropriate format is used.

func (*Script) Generate

func (s *Script) Generate(name string) ([]byte, error)

Generate will return the byte value for the specified script type for the current public key

func (*Script) Out

func (s *Script) Out(name string) (*Out, error)

Out returns a Out object matching the requested script

type SolanaAccountMeta

type SolanaAccountMeta struct {
	Pubkey     SolanaKey
	IsSigner   bool
	IsWritable bool
}

SolanaAccountMeta describes an account referenced by an instruction.

type SolanaCompiledInstruction

type SolanaCompiledInstruction struct {
	ProgramIDIndex uint8
	AccountIndices []uint8
	Data           []byte
}

SolanaCompiledInstruction is an instruction with account references replaced by indices into the message's account key array.

type SolanaInstruction

type SolanaInstruction struct {
	ProgramID SolanaKey
	Accounts  []SolanaAccountMeta
	Data      []byte
}

SolanaInstruction is a high-level instruction before account compilation.

func SolanaTransferInstruction

func SolanaTransferInstruction(from, to SolanaKey, lamports uint64) SolanaInstruction

SolanaTransferInstruction returns a System Program transfer instruction that moves lamports from one account to another.

type SolanaKey

type SolanaKey [32]byte

SolanaKey is a 32-byte public key used to identify accounts on the Solana network.

func ParseSolanaKey

func ParseSolanaKey(s string) (SolanaKey, error)

ParseSolanaKey parses a base58-encoded string into a SolanaKey.

func (SolanaKey) IsZero

func (k SolanaKey) IsZero() bool

IsZero reports whether the key is all zeros.

func (SolanaKey) String

func (k SolanaKey) String() string

String returns the base58 encoding of the key.

type SolanaMessage

type SolanaMessage struct {
	Header          SolanaMessageHeader
	AccountKeys     []SolanaKey
	RecentBlockhash SolanaKey
	Instructions    []SolanaCompiledInstruction
}

SolanaMessage is the message portion of a Solana transaction.

func (*SolanaMessage) MarshalBinary

func (msg *SolanaMessage) MarshalBinary() ([]byte, error)

MarshalBinary serializes the message into the Solana wire format.

func (*SolanaMessage) UnmarshalBinary

func (msg *SolanaMessage) UnmarshalBinary(data []byte) error

UnmarshalBinary deserializes a message from the Solana wire format.

type SolanaMessageHeader

type SolanaMessageHeader struct {
	NumRequiredSignatures       uint8
	NumReadonlySignedAccounts   uint8
	NumReadonlyUnsignedAccounts uint8
}

SolanaMessageHeader contains the counts needed to distinguish signer and readonly accounts in a transaction message.

type SolanaTx

type SolanaTx struct {
	Signatures [][]byte
	Message    SolanaMessage
}

SolanaTx represents a Solana legacy (unversioned) transaction.

func NewSolanaTx

func NewSolanaTx(feePayer, recentBlockhash SolanaKey, instructions ...SolanaInstruction) *SolanaTx

NewSolanaTx compiles a set of high-level instructions into a transaction. The fee payer is always placed first in the account list as a writable signer.

func (*SolanaTx) Hash

func (tx *SolanaTx) Hash() ([]byte, error)

Hash returns the transaction ID, which is the first signature (64 bytes).

func (*SolanaTx) MarshalBinary

func (tx *SolanaTx) MarshalBinary() ([]byte, error)

MarshalBinary serializes the transaction into the Solana wire format.

func (*SolanaTx) Sign

func (tx *SolanaTx) Sign(keys ...ed25519.PrivateKey) error

Sign signs the transaction message with the provided Ed25519 private keys. Keys are matched to signature slots by their public key.

func (*SolanaTx) UnmarshalBinary

func (tx *SolanaTx) UnmarshalBinary(data []byte) error

UnmarshalBinary deserializes a transaction from the Solana wire format.

type Transaction

type Transaction interface {
	encoding.BinaryMarshaler
	encoding.BinaryUnmarshaler
	Hash() ([]byte, error)
}

Transaction is the common interface for cryptocurrency transactions that can be serialized to binary and produce a hash.

Jump to

Keyboard shortcuts

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