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
  1. Guides
  2. SDKs
  3. TypeScript
  4. Low Level

Signatures

A Transaction Signature serves as strong evidence that the transaction has been authorized by the holder of the private key corresponding to an associated public key. This document provides information about the structure, serialization and pre-image format for these signatures.

Data Structure

The TransactionSignature class extends the Signature class, inheriting its basic properties of r and s, which are components of the ECDSA (Elliptic Curve Digital Signature Algorithm) signature. Additionally, it introduces a scope variable which is specific to the context of transaction signing, indicating the parts of the transaction the signature commits to.

The class defines several static readonly properties representing the SIGHASH types for the scope:

  • SIGHASH_ALL: The signature commits to all outputs of the transaction, ensuring none can be changed without invalidating the signature.

  • SIGHASH_NONE: The signature commits to no outputs, allowing others to add outputs to the transaction.

  • SIGHASH_SINGLE: The signature commits to exactly one output, the one with the same index as the input the signature is for. This allows for independent adjustment of outputs in multi-output transactions.

  • SIGHASH_ANYONECANPAY: Modifies the behavior of the other types by only committing to the current input, allowing others to add or remove other inputs.

  • SIGHASH_FORKID: Currently always enabled in BSV.

Serialization and Formats

The TransactionSignature class includes methods for serializing and deserializing transaction signatures, useful for referencing them within scripts, among other things.

  • format(): This static method prepares the transaction data for signing by creating a preimage according to the specified SIGHASH type. It considers various components like inputs, outputs, the transaction sequence, and lock time. Useful for generating the data that will be signed to produce a transaction signature.

  • fromChecksigFormat(): Deserializes a script stack element into a TransactionSignature instance, useful for parsing signatures from raw transaction data.

  • toChecksigFormat(): Serializes the signature back into a format that can be embedded in a script. This includes converting the ECDSA components (r and s) into DER format, followed by the scope (SIGHASH flags) to indicate which components are signed.

The TransactionSignature encapsulates the complexity of transaction signing and signature serialization. You can make use of the static .format() method to compute the signatures you need, enabling a wide variety of applications.

Using the Signature Preimage Formatter

Here's an example of formatting a signature preimage for use in a Transaction:

import { P2PKH, Transaction, PrivateKey, TransactionSignature, UnlockingScript, Hash } from '@bsv/sdk'

// Initialize the script template, source TX, and the TX we'll be working on adding a signature for.
const p2pkh = new P2PKH()
const sourceTx = Transaction.fromHex('0200000001849c6419aec8b65d747cb72282cc02f3fc26dd018b46962f5de48957fac50528020000006a473044022008a60c611f3b48eaf0d07b5425d75f6ce65c3730bd43e6208560648081f9661b0220278fa51877100054d0d08e38e069b0afdb4f0f9d38844c68ee2233ace8e0de2141210360cd30f72e805be1f00d53f9ccd47dfd249cbb65b0d4aee5cfaf005a5258be37ffffffff03d0070000000000001976a914acc4d7c37bc9d0be0a4987483058a2d842f2265d88ac75330100000000001976a914db5b7964eecb19fcab929bf6bd29297ec005d52988ac809f7c09000000001976a914c0b0a42e92f062bdbc6a881b1777eed1213c19eb88ac00000000')
const tx = new Transaction(
    1, //version
    [{
        sourceTransaction: sourceTx,
        sourceOutputIndex: 0,
        sequence: 0xffffffff
    }],
    [{ // outputs
        lockingScript: p2pkh.lock('176ayvhKue1C5StD31cTsdN1hwotw59jsR'),
        satoshis: 1000
    }],
    0 // lock time
)

// The private key we will use for signing
const privateKey = new PrivateKey(42) // Replace

// Let's decide which input index we're signing
const inputIndex = 0

// We'll sign all inputs and outputs with this signature.
let signatureScope = TransactionSignature.SIGHASH_FORKID | TransactionSignature.SIGHASH_ALL

const otherInputs = [...tx.inputs]
const [input] = otherInputs.splice(inputIndex, 1)
if (typeof input.sourceTransaction !== 'object') {
    throw new Error(
        'The source transaction is needed for transaction signing.'
    )
}

// The pre-image is the data that we are incorporating into the signature.
// It needs a few important details about the output we're spending and the new transaction we're creating.
const preimage = TransactionSignature.format({
    // The source TXID of the output we're spending needs to be provided.
    sourceTXID: input.sourceTransaction.id('hex') as string,

    // Identify the output index in the source transaction so we know where the coins come from.
    sourceOutputIndex: input.sourceOutputIndex,

    // Identify the amount of satoshis that are in the source output.
    sourceSatoshis: input.sourceTransaction.outputs[input.sourceOutputIndex].satoshis as number,

    // Identify the version of the new transaction you are creating, that will spend the source output.
    transactionVersion: tx.version,

    // Stipulate any other inputs (with the current input removed from the list) in the new transaction
    // that will be included in the signature. Note that with SIGHASH_ANYONECANPAY, this can be empty.
    otherInputs,

    // Stipulate the index of the current input in the new transaction you are working to create.
    inputIndex,

    // Stipulate the outputs to the new transaction you are creating.
    // Note that if you are using SIGHASH_NONE, this can be empty.
    // If you are using SIGHASH_SINGLE, it could be a "sparse array" with only the output at the same index as the inputIndex populated.
    outputs: tx.outputs,

    // Provide the current sequence number of the input that you are working on signing.
    inputSequence: input.sequence,

    // Provide the portion of the script in which you are working.
    // In most simple use-cases (that don't make use of OP_CODESEPARATOR), this is just the locking script from the source output.
    subscript: input.sourceTransaction.outputs[input.sourceOutputIndex].lockingScript,

    // Provide the lock time for the new transaction you are working to create.
    lockTime: tx.lockTime,

    // Finally, provide the SIGHASH flags you wish to include in the preimage that will be generated.
    scope: signatureScope
})

// The result will be a preimage that can be signed, and included in scripts.

// We sign the hash of the preimage.
// Because the `.sign()` method also performs a hash, the result is the "double-hash" needed by Bitcoin.
const rawSignature = privateKey.sign(Hash.sha256(preimage))

// Now, we construct a TransactionSignature from the ECDSA signature, for conversion to Checksig format.
const sig = new TransactionSignature(
    rawSignature.r,
    rawSignature.s,
    signatureScope
)

// Then we convert it so it can be used in a script
const sigForScript = sig.toChecksigFormat()

// Finally, we could go on to make any kind of needed unlocking script with the signature..
const pubkeyForScript = privateKey.toPublicKey().encode(true) as number[]
const script = new UnlockingScript([
    { op: sigForScript.length, data: sigForScript },
    { op: pubkeyForScript.length, data: pubkeyForScript }
])
console.log('Signature was computed! P2PKH Unlocking Script:', script.toHex())

First, we set up the data we wanted to sign. Then, we created a pre-image, hashed it, and signed it with a private key using ECSA. Then, we created a new TransactionSignature instance with the ECDSA signature, so that we could convert it into Checksig format. At this point, you could use the transaction signature in a script to help unlock a UTXO, enabling you to unlock and spend the associated Bitcoins or other digital assets.

PreviousNumbers & PointsNext42

Last updated 11 months ago

Was this helpful?