LogoLogo
LogoLogo
  • Intro
    • Welcome
    • The Benefits of BSV Blockchain
    • What Can I Do?
    • Overview of GitHub repositories
    • Quick Start
  • Protocol
    • Introduction
    • BSV Blockchain
      • Blocks
      • Transactions
      • Proof of Work
      • Capabilities
      • Economic Model of Governance
      • Digital Asset Recovery
    • Network Policies
      • High-Level Architecture
      • Mining
      • Standard and Local Policies
      • Consensus Rules
      • Local Policies
    • Node Operations
      • Node Software
      • Bitcoin Server Network (BSN)
      • ChainTracker
      • Transaction Validation
      • UTXO Storage
      • Mempool
      • Block Assembler
      • Block Validation
      • Mining Software
      • Pruning transactions
      • Responsibilities of a Node
    • SPV Wallets, Overlays and SPV Processes
      • Simplified Payment Verification (SPV)
      • Instant Payments
      • Integrity Checks
      • SPV Wallets & Overlays
    • Transaction Lifecycle
      • Transaction Inputs and Outputs
      • Script
      • Transaction Flow
      • Constructing a transaction
      • Sequence Number and Time Locking
      • Transaction Templates
      • Transaction Processing
      • Opcodes used in Script
    • Privacy
      • Keys and Identity
      • Private vs Anonymous
      • Digital Signatures
      • Privacy on the Public Blockchain
  • Network Access Rules
    • Rules
      • Table of Contents
      • Background to the Rules
      • PART I - MASTER RULES
      • PART II - GENERAL RULES
      • PART III - ENFORCEMENT RULES
      • PART IV - DISPUTE RESOLUTION RULES
      • PART V - INTERPRETIVE RULES
    • FAQs
      • Miners
      • Professionals
      • Users
  • Important Concepts
    • High Level
      • Web3
      • Timestamping
      • SPV
      • UTXO vs Account Based
      • Linked Keys
      • Smart Contracts
    • Details
      • Hash Functions
      • Merkle Trees
      • Sighash Flags
      • Script
      • SPV
        • Deep Dive
        • Payments Flow
        • Data Models
        • Broadcasting
  • Network Topology
    • Mandala Upgrade
    • Nodes
      • SV Node
        • Architecture
        • System Requirements
        • Installation
          • SV Node
            • Configuration
            • AWS Volumes Setup
            • DDOS Mitigation
            • Docker
            • Genesis Settings
            • GetMiningCandidate
            • GKE
            • Network Environments
              • Regtest
              • STN
              • Testnet
        • Alert System
          • Alert Messages
          • Running the Alert System
            • Startup Script
          • Webhooks
        • RPC Interface
          • RPC Methods
        • Frequently Asked Questions
          • Blocks
          • Initial Block Download
          • Transactions
          • Log File Warnings
          • Safe Mode
          • Bug Bounty
        • Chronicle Release
      • Teranode
    • Overlay Services
      • Overlay Example
    • SPV Wallet
      • Quickstart
      • Key Concepts
      • AWS Deployment
        • Installation
        • Manage & Maintain
        • Update
        • Delete
      • Components
        • SPV Wallet Server
        • Storage
        • Web Admin
        • Block Headers Service
        • Web App & API
      • Who is it for?
      • Functionality & Roadmap
      • Contribute
      • Developers Guide
        • SPV Wallet
          • Authentication
          • Configuration
          • Notification
        • Go Client
          • Authentication
        • JS Client
          • Authentication
        • Admin
        • Keygen
        • Block Headers Service
          • Authentication
          • Configuration
      • Additional Components
  • paymail
    • Overview
    • BRFC Specifications
      • Specification Documents
      • BRFC ID Assignment
    • Service Discovery
      • Host Discovery
      • Capability Discovery
    • Public Key Infrastructure
    • Payment Addressing
      • Basic Address Resolution
      • Sender Validation
      • Receiver Approvals
      • PayTo Protocol Prefix
    • Verify Public Key Owner
    • Recommendations
  • Guides
    • Local Blockchain Stack
      • Mockchain Stack
    • Business Use Cases
      • Creating a Tranche of Event Tickets
    • SDKs
      • Concepts
        • BEEF
        • Fees
        • SPV
        • Transactions
        • Op Codes
        • Script Templates
        • Signatures
        • Verification
      • TypeScript
        • Node, CommonJS
        • React
        • Low Level
          • Verification
          • ECDH
          • Numbers & Points
          • Signatures
          • 42
          • ECDSA
          • Hmacs
          • Keys
          • Scripts
        • Examples
          • Creating a Simple Transaction
          • Verifying a BEEF Structure
          • Creating Transactions with Inputs, Outputs and Templates
          • Creating the R-puzzle Script Template
          • Message Encryption and Decryption
          • Message Signing
          • Building a Custom Transaction Broadcast Client
          • Verifying Spends with Script Intrepreter
          • BIP32 Key Derivation with HD Wallets
          • Using Type 42 Key Derivation for Bitcoin Wallet Management
          • Creating a Custom Transaction Fee Model
          • Building a Pulse Block Headers Client
          • Using ECIES Encryption
      • Go
        • Examples
          • Simple Tx
          • Keys
          • Encryption
          • Broadcasting
          • Inscribing
          • Data Markers
          • Linked Keys
          • ECIES
          • Fees
          • HD Keys
          • Headers
          • Secure Messages
          • Merkle Path Verification
      • Python
        • Examples
          • Simple Tx
          • Verifying BEEF
          • Complex Tx
          • Script Templates
          • Encryption
          • Message Signing
          • Building A Custom Broadcaster
          • HD Wallets
          • Linked Keys
          • Fees
          • Merkle Path Verification
          • ECIES
  • BSV Academy
    • Getting Started
    • BSV Basics: Protocol and Design
      • Introduction
        • Bit-Coin
      • The BSV Ledger
        • The Ledger
        • Triple Entry Accounting
        • Example
      • Coins and Transactions
        • Coins
        • Transactions
        • Transaction Fees
      • Theory
      • Conclusion
    • BSV Enterprise
      • Introduction
      • About BSV Blockchain
        • Introduction
        • Safe, Instant Transactions at a Predictably Low Cost
          • Reliably Low Fees
          • Comparison to Legacy Transaction Systems
          • Payment Channels
        • Scalability to Accommodate Global Demand
          • Big Blocks Show Big Potential
        • A Plan for Regulatory Acceptance
          • Ready-made Compliance
          • The Open BSV License
        • Protocol Stability
          • Building Foundations on a Bedrock of Stone
      • Technical Details
        • The Network
          • The Small World Network
          • Robust In Its Unstructured Simplicity
        • The Bitcoin SV Node Client
          • Teranode - The Future of BSV
        • The Protocol - Simple, Robust and Unbounded
          • What is the BSV Protocol?
        • Proof of Work
          • The Algorithm
          • Efficiency of Proof of Work
        • Privacy and Identity
        • Permissions and Privacy
      • Resources and Tools
        • The Technical Standards Comittee
          • TSC Principles
          • Standard Development Process
          • Status of Current and In-progress Standards
        • The Working Blockchain
          • Pruning to Create a Working Blockchain
          • Building a Working Blockchain from a List of Block Headers
          • A World View Backed by Proof of Work
    • Hash Functions
      • What are Hash Functions?
        • The Differences Between Hashing and Encryption
        • The Three Important Properties of Hash Functions
        • The Hash Functions Found in BSV
      • Base58 and Base58Check
        • What is Base58 and Why Does Bitcoin use it?
        • What is Base58 and How Does BSV use it?
      • SHA256
        • BSV Transactions and SHA-256
        • BSV Blocks and SHA-256
        • Proof-of-Work and HASH-256
      • Walkthrough Implementation of SHA-256 in Golang
        • Overview of SHA-256
        • SHA-256 Input and Processing
        • SHA-256 Compression
        • SHA-256 Final Value Construction and Output
      • RIPEMD-160
        • BSV Addresses & WIFs
      • Walkthrough Implementation of RIPEMD-160 in Golang
        • Overview of RIPEMD-160
        • RIPEMD-160 Input and Processing
        • RIPEMD-160 Compression
        • RIPEMD-160 Final Value Construction and Output
      • Doubla Hashing and BSV's Security
        • Why is Double Hashing Used in BSV
        • Hash Functions and BSV's Security Model
    • Merkle Trees
      • The Merkle Tree
        • What is a Merkle Tree?
        • Why use a Merkle Tree?
        • Merkle Trees in Action
      • Merkles Trees in BSV
        • The Data Elements
        • Transaction Merkle Trees
        • Transaction Merkle Trees in Action
      • Merkle Trees and the Block Header
        • What is the Block Header
        • The Hash Puzzle
        • Proof-of-Work in Action
      • Merkle trees and Verifying Proof of Work
        • Broadcasting the Block
        • The Coinbase Transaction
        • Data Integrity of the Block
        • Saving Disk Space
      • Standarised Merkle Proof
        • What is a Merkle Proof?
        • The BSV Unified Merkle Path (BUMP) Standard
        • Simple and Composite Proofs
      • Merkle Trees and Simplified Payment Verification
        • SPV
        • Offline Payments
    • Digital Signatures
      • What are Digital Signatures
        • Background
        • Introduction
        • Digital Signatures Protocol
        • Properties of Digital Signatures
      • ECDSA Prerequisites
        • Disclaimer
        • Modular Arithmetic
        • Groups, Rings and Finite Fields
        • Discrete Logarithm Problem
        • Elliptic Curve Cryptography (ECC)
        • Discrete Logarithm Problem with Elliptic Curves
      • ECDSA
        • Introduction
        • ECDSA
        • Further Discussion
      • BSV and Digital Signatures
        • Introduction
        • BSV Transaction
        • ECDSA (secp256k1) for BSV Transaction
        • Summary
        • Signed Messages
        • Miner Identification and Digital Signatures
    • BSV Theory
      • Abstract
        • Peer-to-Peer Cash
        • Digital Signatures and Trusted Third Parties
        • Peer-to-Peer Network
        • Timechain and Proof-of-Work
        • CPU Power
        • Cooperation in the Network
        • Network Structure
        • Messaging Between Nodes
      • Introduction
        • Commerce on the Internet
        • Non Reversible Transactions
        • Privacy in Commerce
        • The Paradigm of Fraud Acceptance
        • What is Needed...
        • Protecting Sellers From Fraud
        • Proposed Solution
        • Security and Honesty
      • Transactions
        • Electronic Coins
        • Spending a Coin
        • Payee Verification
        • Existing Solutions
        • First Seen Rule
        • Broadcasting Transactions
        • Achieving Consensus
        • Proof of Acceptance
      • Timestamp Server
        • Timestamped Hashes
        • A Chain of Timestamped Hashes
      • Proof of Work
        • Hashcash
        • Scanning Random Space
        • Nonce
        • Immutable Work
        • Chain Effort
        • One CPU, One Vote
        • The Majority Decision
        • The Honest Chain
        • Attacking the Longest Chain
        • Controlling the Block Discovery Rate
      • Network
        • Running the Network
        • The Longest Chain
        • Simultaneous Blocks
        • Breaking the Tie
        • Missed Messages
      • Incentive
        • The Coinbase Transaction
        • Coin Distribution
        • Mining Analogy
        • Transaction Fees
        • The End of Inflation
        • Encouraging Honesty
        • The Attacker's Dilemma
      • Reclaiming Disk Space
        • Spent Transactions
        • The Merkle Tree
        • Compacting Blocks
        • Block Headers
      • Simplified Payment Verification
        • Full Network Nodes
        • Merkle Branches
        • Transaction Acceptance
        • Verification During Attack Situations
        • Maintaining an Attack
        • Invalid Block Relay System
        • Businesses Running Nodes
      • Combining and Splitting Value
        • Dynamically Sized Coins
        • Inputs and Outputs
        • A Typical Example
        • Fan Out
      • Privacy
        • Traditional Models
        • Privacy in Bitcoin
        • Public Records
        • Stock Exchange Comparison
        • Key Re-Use
        • Privacy - Assessment 2
        • Linking Inputs
        • Linking the Owner
      • Calculations
        • Attacking the Chain
        • Things the Attacker Cannot Achieve
        • The Only Thing an Attacker Can Achieve
        • The Binomial Random Walk
        • The Gambler's Ruin
        • Exponential Odds
        • Waiting For Confirmation
        • Attack Via Proof of Work
        • Vanishing Probabilities
      • Conclusion
        • Conclusion Explained
    • Introduction to Bitcoin Script
      • Chapter 1: About Bitcoin Script
        • 01 - Introduction
        • 02 - FORTH: A Precursor to Bitcoin Script
        • 03 - From FORTH to Bitcoin Script
        • 04 - Bitcoin's Transaction Protocol
        • 05 - Transaction Breakdown
        • 06 - nLockTime
        • 07 - The Script Evaluator
      • Chapter 2: Basic Script Syntax
        • 01 - Introduction
        • 02 - Rules Around Data and Scripting Grammar
        • 03 - The Stacks
      • Chapter 3: The Opcodes
        • 01 - Introduction
        • 02 - Constant Value and PUSHDATA Opcodes
        • 03 - IF Loops
        • 04 - OP_NOP, OP_VERIFY and its Derivatives
        • 05 - OP_RETURN
        • 06 - Stack Operations
        • 07 - Data transformation
        • 08 - Stack Data Queries
        • 09 - Bitwise transformations and Arithmetic
        • 10 - Cryptographic Functions
        • 11 - Disabled and Removed Opcodes
      • Chapter 4: Simple Scripts
        • 01 - Introduction
        • 01 - Pay to Public Key (P2PK)
        • 02 - Pay to Hash Puzzle
        • 03 - Pay to Public Key Hash (P2PKH)
        • 04 - Pay to MultiSig (P2MS)
        • 05 - Pay to MultiSignature Hash (P2MSH)
        • 06 - R-Puzzles
      • Chapter 5: OP_PUSH_TX
        • 01 - Turing Machines
        • 02 - Elliptic Curve Signatures in Bitcoin
        • 03 - OP_PUSH_TX
        • 04 - Signing and Checking the Pre-Image
        • 05 - nVersion
        • 06 - hashPrevouts
        • 07 - hashSequence
        • 08 - Outpoint
        • 09 - scriptLen and scriptPubKey
        • 10 - value
        • 11 - nSequence
        • 12 - hashOutputs
        • 13 - nLocktime
        • 14 - SIGHASH flags
      • Chapter 6: Conclusion
        • Conclusion
    • BSV Infrastructure
      • The Instructions
        • The Whitepaper
        • Steps to Run the Network
        • Step 1
        • Step 2
        • Step 3
        • Step 4
        • Step 5
        • Step 6
      • Rules and their Enforcement
        • Introduction
        • Consensus Rules
        • Block Consensus Rules
        • Transaction Consensus Rules
        • Script Language Rules
        • Standard Local Policies
      • Transactions, Payment Channels and Mempools
      • Block Assembly
      • The Small World Network
        • The Decentralisation of Power
        • Incentive Driven Behaviour
        • Lightspeed Propagation of Transactions
        • Ensuring Rapid Receipt and Propagation of New Blocks
        • Hardware Developments to Meet User Demand
        • Novel Service Delivery Methods
        • MinerID
      • Conclusion
  • Research and Development
    • BRCs
    • Technical Standards
  • Support & Contribution
    • Join Our Discord
    • GitHub
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
Export as PDF

Last updated 9 months ago

Was this helpful?

This guide walks you through the steps of creating a simple Bitcoin transaction. To get started, let's explain some basic concepts around Bitcoin transactions.

Understanding and Creating Transactions

Transactions in Bitcoin are mechanisms for transferring value and invoking smart contract logic. The Transaction class in the BSV SDK encapsulates the creation, signing, and broadcasting of transactions, also enabling the use of Bitcoin's scripting language for locking and unlocking coins.

Creating and Signing a Transaction

Consider the scenario where you need to create a transaction. The process involves specifying inputs (where the bitcoins are coming from) and outputs (where they're going). Here's a simplified example:

Code Walk Through

Private Key and Address

  • PrivateKeyFromWif is used to extract the private key from a Wallet Import Format (WIF) string. This private key is then used to generate a corresponding public key.

  • NewAddressFromPublicKey generates a Bitcoin address from the public key. The second argument true indicates that the address will be in the compressed format.

Source Transaction

  • sourceRawtx: A hexadecimal string representing a raw Bitcoin transaction. This transaction serves as the input to the new transaction you are creating.

  • NewTransactionFromHex: Converts the raw transaction hex string into a Transaction object.

  • sourceMerklePathHex: This hex string represents the Merkle path, which is used for verifying the inclusion of the transaction in a block.

  • NewMerklePathFromHex: Converts the Merkle path hex string into a MerklePath object.

  • sourceTransaction.MerklePath = merklePath: Associates the Merkle path with the source transaction.

New Transaction

  • NewTransaction creates a new, empty transaction object that will be populated with inputs and outputs.

Unlocking Script

  • p2pkh.Unlock generates an unlocking script (scriptSig) from the private key. This script will be used to prove ownership of the bitcoins being spent.

  • The Unlock method creates a template for the unlocking script, which can be used to satisfy the conditions of a P2PKH locking script.

Transaction Input

  • AddInput adds an input to the transaction. The input references the source transaction using its transaction ID (SourceTXID) and specifies the output index (SourceTxOutIndex).

  • The input also includes the unlockingScriptTemplate, which is necessary to unlock the bitcoins in the referenced output.

Locking Script

  • p2pkh.Lock creates a locking script (scriptPubKey) for the recipient’s address. This script ensures that only the recipient, who can provide a valid unlocking script, can spend the bitcoins.

Transaction Output

  • AddOutput adds an output to the transaction. The output specifies the locking script and the amount of bitcoins to send (in satoshis).

Sign Transaction

  • tx.Sign signs the transaction. This involves generating digital signatures for each input, which are included in the unlocking scripts. The signatures prove that the sender has the authority to spend the bitcoins.

Transaction Formats

BEEF: This outputs the transaction in a custom format defined by , which may be useful for debugging or analysis.

EF: This outputs the transaction in another custom format , providing a different view of the transaction data.

package main

import (
	"encoding/hex"
	"log"

	ec "github.com/bitcoin-sv/go-sdk/primitives/ec"
	"github.com/bitcoin-sv/go-sdk/script"
	"github.com/bitcoin-sv/go-sdk/transaction"
	"github.com/bitcoin-sv/go-sdk/transaction/template/p2pkh"
)

// https://goplay.tools/snippet/bnsS-pA56ob
func main() {
	// examlpe wif and associated address
	priv, _ := ec.PrivateKeyFromWif("KznvCNc6Yf4iztSThoMH6oHWzH9EgjfodKxmeuUGPq5DEX5maspS")
	address, _ := script.NewAddressFromPublicKey(priv.PubKey(), true)

	// Source transaction data
	sourceRawtx := "010000000138c7c61c14ffb063c3bb2664041a3e29ea6ea0412a0c18ff725ba4e9e12afae2030000006a47304402203e9ab" +
		"8e4c14addf3b4741540b556cfb0e0efb67dc1a7b5ce84c3ac56b3fd447802203c9f49f7bd893ebd7060176dfc36bcaff9d2c443d9a0dd6" +
		"cd2d59b372c024d20412102798913bc057b344de675dac34faafe3dc2f312c758cd9068209f810877306d66ffffffff02dc05000000000" +
		"0002076a914eb0bd5edba389198e73f8efabddfc61666969ff788ac6a0568656c6c6faa0d0000000000001976a914eb0bd5edba389198e" +
		"73f8efabddfc61666969ff788ac00000000"
	sourceMerklePathHex := "fed7c509000a02fddd010069464172a5d0cd3d641516166091ab84d230e8848ac9ccdc93f185d7b1b07902fddc0" +
		"1029d81a1815050f3a7bf8392e077481151af50a011a10708d4fc480a8ead76b41101ef00a93658c713530e49e2d6cad2529ecf06eb206" +
		"20b9e1d3bdf75dbef8f509a5cc101760040808d97bfcb804293013e2108c4df25996ea9ba517671ff721c7be73dbfc3c5013a000435fef" +
		"874132a7ebda11760ad63eccf37ba82f41793d6453f744b0873829c77011c000a0d32242d744e2007e8c3ccbfd761380d7c4340a90d825" +
		"5cd608ad307752cd8010f007718f8c034a5ff0adf9c3c337660c4592bd6a6ff10de2d8f01afbb8c65f9143e0106006214d394450c84eab" +
		"dcf04e7ecc6b893e1649ecc48bb3a6f38d48afcb0f2bc6a0102006a5fe10c65d3ce6950b4cbbd2bd584bcec0263c5178c3226bde14d7e3" +
		"07d4557010000a14df02e34b74d15dbcd0c7896b3dfb8ffb136cc3ba61ec118b37ddc70974cd5010100a5f147afb93db1ffe573b69b7c8" +
		"4abc3582c6cd7f3eaf82b4142d7557c28f0ae"

	sourceTransaction, _ := transaction.NewTransactionFromHex(sourceRawtx)
	merklePath, _ := transaction.NewMerklePathFromHex(sourceMerklePathHex)
	sourceTransaction.MerklePath = merklePath

	// Create a new transaction
	tx := transaction.NewTransaction()

	// Create a new P2PKH unlocker from the private key
	// Add an input
	unlockingScriptTemplate, err := p2pkh.Unlock(priv, nil)
	if err != nil {
		log.Fatal(err.Error())
	}
	tx.AddInput(&transaction.TransactionInput{
		SourceTXID:              sourceTransaction.TxIDBytes(),
		SourceTxOutIndex:        0,
		SourceTransaction:       sourceTransaction,
		UnlockingScriptTemplate: unlockingScriptTemplate,
		SequenceNumber:          transaction.DefaultSequenceNumber,
	})

	// Create a new P2PKH lock from the address
	lockScript, err := p2pkh.Lock(address)
	if err != nil {
		log.Fatal(err.Error())
	}
	// Add the outputs
	tx.AddOutput(&transaction.TransactionOutput{
		LockingScript: lockScript,
		Satoshis:      1,
	})
	if err != nil {
		log.Fatal(err.Error())
	}

	// Sign the transaction
	if err := tx.Sign(); err != nil {
		log.Fatal(err.Error())
	}

	beef, _ := tx.BEEF()
	log.Printf("beef: %s\n", hex.EncodeToString(beef))

	ef, _ := tx.EF()
	log.Printf("ef: %s\n", hex.EncodeToString(ef))
}
  1. Guides
  2. SDKs
  3. Go
  4. Examples

Simple Tx

PreviousExamplesNextKeys
  • Understanding and Creating Transactions
  • Creating and Signing a Transaction
  • Code Walk Through
  • Private Key and Address
  • Source Transaction
  • New Transaction
  • Unlocking Script
  • Transaction Input
  • Locking Script
  • Transaction Output
  • Sign Transaction
  • Transaction Formats
BRC-62
BRC-30