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
  • Transaction Input and Outputs
  • Creating a Transaction
  • Adding Inputs and Outputs
  • Transaction Inputs
  • Transaction Outputs
  • Change and Fee Computation
  • Signing and Signature Validity
  • Serialization and Broadcast
  • SPV and Serialization Formats

Was this helpful?

Edit on GitHub
Export as PDF
  1. Guides
  2. SDKs
  3. TypeScript
  4. Examples

Creating Transactions with Inputs, Outputs and Templates

PreviousVerifying a BEEF StructureNextCreating the R-puzzle Script Template

Last updated 1 year ago

Was this helpful?

In Bitcoin, transactions contain inputs and outputs. The outputs are locked with scripts, and the inputs redeem these scripts by providing the correct unlocking solutions. This guide will show you how to create transactions that make use of custom inputs, outputs, and the associated script templates. For a more straightforward example, check out .

Transaction Input and Outputs

All Bitcoins are locked up in Bitcoin transaction outputs. These outputs secure the coins by setting constraints on how they can be consumed in future transaction inputs. This security mechanism makes use of "scripts" — programs written in a special predicate language. There are many types of locking programs, embodying the multitude of BSV use-cases. The BSV SDK ships with a script templating system, making it easy for developers to create various types of scripts and abstracting away the complexity for end-users. You can learn about script templates .

Creating a Transaction

To create a transaction with the SDK, you can either use the constructor:

  • Use the constructor and pass in arrays of inputs and outputs, or

  • Construct a blank transaction, then call the addInput and addOutput methods

const tx = new Transaction(version, inputsArray, outputsArray, lockTime)
// or
const tx = new Transaction()
    .addInput(inputA)
    .addInput(inputB)
    .addOutput(outputA)
tx.version = version
tx.lockTime = lockTime

Note that the version and lock time parameters are optional.

Adding Inputs and Outputs

When constructing a Bitcoin transaction, inputs and outputs form the core components that dictate the flow of bitcoins. Here’s how to structure and add them to a transaction:

Transaction Inputs

An input in a Bitcoin transaction represents the bitcoins being spent. It's essentially a reference to a previous transaction's output. Inputs have several key components:

  • sourceTransaction or sourceTXID: A reference to either the source transaction (another Transaction instance), its TXID. Referencing the transaction itself is always preferred because it exposes more information to the library about the outputs it contains.

  • sourceOutputIndex: A zero-based index indicating which output of the referenced transaction is being spent.

  • sequence: A sequence number for the input. It allows for the replacement of the input until a transaction is finalized. If omitted, the final sequence number is used.

  • unlockingScript: This script proves the spender's right to access the bitcoins from the spent output. It typically contains a digital signature and, optionally, other data like public keys.

  • unlockingScriptTemplate: A template that provides a method to dynamically generate the unlocking script.

Next, we'll add an R-puzzle input into this transaction using the `RPuzzle`` template.

Example: Adding an Input

const sourceTransaction = Transaction.fromHex('...')
const puz = new RPuzzle()
const k = new BigNumber(1)
const unlockingScriptTemplate = puz.unlock(k)
let txInput = {
    sourceTransaction,
    sourceOutputIndex: 0,
    unlockingScriptTemplate
}

const myTx = new Transaction()
myTx.addInput(txInput)

Transaction Outputs

Outputs define where the bitcoins are going and how they are locked until the next spend. Each output includes:

  • satoshis: The amount of satoshis (the smallest unit of Bitcoin) being transferred. This value dictates how much value the output holds.

  • lockingScript: A script that sets the conditions under which the output can be spent. It's a crucial security feature, often requiring a digital signature that matches the recipient's public key.

  • change: An optional boolean flag indicating if the output is sending change back to the sender.

We will now add an R-puzzle output to a transaction, making use of the script template.

Example: Adding an Output

// We must first obtain an R-value for the template
const pubkey = PublicKey.fromString('...')
pubkey.x.umod(c.n).toArray()
r = r[0] > 127 ? [0, ...r] : r
const puz = new RPuzzle()
const lockingScript = puz.lock(r)

let txOutput = {
    satoshis: 1000, // Amount in satoshis
    lockingScript,
    change: false // Not a change output, it has a defined number of satoshis
}

myTx.addOutput(txOutput)

Change and Fee Computation

The transaction fee is the difference between the total inputs and total outputs of a transaction. Miners collect these fees as a reward for including transactions in a block. The amount of the fee paid will determine the quality of service provided my miners, subject to their policies.

If the total value of the inputs exceeds the total value you wish to send (plus the transaction fee), the excess amount is returned to you as "change." Change is sent back to a destination controlled by the sender, ensuring that no value is lost. When you set the change property on an output to true, you don't need to define a number of satoshis. This is because the library computes the number of satoshis for you, when the .fee() method is called.

In summary:

  1. After all funding sources and recipient outputs are added, add at least one output where change is true, so that you capture what's left over after you send. Set up a locking script you control so that you can later spend your change.

  2. Then, call the .fee() method to compute the change amounts across all change outputs, and leave the rest to the miner. You can specify a custom fee model if you wish, but the default should suffice for most use-cases.

In our above code, we already added a change output — now, we can just compute the fees before transaction signing.

// Compute the correct amounts for change outputs and leave the rest for the Bitcoin miners
myTx.fee()

Signing and Signature Validity

Once you've defined your inputs and outputs, and once your change has been computed, the next step is to sign your transaction. There are a few things you should note when signing:

  • Only inputs with an unlocking template will be signed. If you provided an unlocking script yourself, the library assumes the signatures are already in place.

  • If you change the inputs or outputs after signing, certain signatures will need to be re-computd, depending on the SIGHASH flags used.

  • If your templates support it, you can produce partial signatures before serializing and sending to other parties. This is especially useful for multi-signature use-cases.

With these considerations in mind, we can now sign our transaction. The RPuzzle unlocking templates we configured earlier will be used in this process.

// Set the input unlocking scripts based on the script templates
myTx.sign()

Serialization and Broadcast

After a transaction is signed, it can be broadcast to the BSV Mining Network, or to relevant Overlay Networks through the SDK.

// get your api key from https://console.taal.com
const apiKey = 'mainnet_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' // replace
await tx.broadcast(new ARC('https://api.taal.com/arc', apiKey))

Alternatively, if you don't want to use the SDK's built-in broadcasting system, you can simply serialize your transaction into a hex string as follows:

// Serialize your transaction
myTx.toHex()

SPV and Serialization Formats

Simplified Payment Verification is a mechanism that enables the recipient of a transaction to verify its legitimacy by providing necessary information, like input transactions and their associated merkle proofs.

Earlier in this guide, we mentioned that you can either reference a sourceTXID or, preferably, a sourceTransaction when linking transaction inputs. The reason why it's preferable to link the entire source transaction is because serializing the transaction in an SPV-compliant way generally requires more information about the outputs being spent.

When properly linked, you can serialize your transactions in the SPV formats as follows:

// Note: Requires use of sourceTransaction instead of sourceTXID for inputs
myTx.toHexBEEF()
// or
myTx.toHexEF()

This enables the transactions to be verified properly by recipients, using the .verify() method:

const incomingTX = Transaction.fromHexBEEF('...')
incomingTX.verify(chainTracker) // Provide a source of BSV block headers to verify

Recipients, with nothing other than a source of BSV block headers, can verify that the transaction properly unlocks and redeems its inputs, thereby creating its outputs. To learn more about setting up a chain tracker with a source of block headers, check out the Pulse example (link to be provided once completed).

how to create a simpler transaction
in the example