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
  • Big Numbers
  • Curves and Points
  • Point Addition and Multiplication

Was this helpful?

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

Numbers & Points

At the base of both symmetric and asymmetric algorithms lie the concept of numbers, large enough to represent a key that can be used in various operations. Further, asymmetric systems based in elliptic curves rely on a way to represent the points on these curves. Both numbers and points have various mathematical operations that enable these algorithms, and this guide will provide an overview of the SDK's implementations of each.

Big Numbers

In JavaScript and TypeScript, natural numbers are limited to 53 bits of precision. This means that it's not possible to have numbers larger than 2 to the power of 53. However, the keys used in secure algorithms, such as those used in Bitcoin, are on the order of 256 bits in length. This means that we need a specialized representation of these large numbers, and the necessary mathematical operations on them.

The SDK's BigNumber class provides this capability. Here's a simple example:

import { BigNumber, Random } from '@bsv/sdk'

const bn1 = new BigNumber(7)
const bn2 = new BigNumber(4)
const bn3 = bn1.add(bn2)
console.log(bn3.toNumber())
// 11

Here, we're creating two "big" numbers and adding them together. These numbers aren't actually very large, but they illustrate the point. We can use larger numbers, generating them randomly, and convert them into hex:

// Generate a BigNumber from 32 random bytes (256 bits, like Bitcoin private keys)
const bn1 = new BigNumber(Random(32))
console.log(bn1.toHex())
// 31af7e86775fbbab9b8618eaad8d9782251cc67ff7366d7f59aee5455119c44f

// Multiply this number by 65536
const bn2 = bn1.muln(65536)

// Printed on the screen, this should be two bytes shfted over in hex
// This amounts to four extra zeroes at the end
console.log(bn2.toHex())
// 31af7e86775fbbab9b8618eaad8d9782251cc67ff7366d7f59aee5455119c44f0000

It's also possible to do many othe operations, like subtraction, division, and conversion into various formats:

const bn1 = new BigNumber(21)
const bn2 = new BigNumber(5)

console.log(bn1.sub(bn2).toNumber()) // 16

// Note that decimal numbers are not supported.
// For division, we are expecting a whole number.
console.log(bn1.div(bn2).toNumber()) // 4

// We can get the remainder with the modulous function.
console.log(bn1.mod(bn2).toNumber()) // 1

// BigNumbers can be imported and exported to various formats
const bn3 = new BigNumber(Random(6))
console.log(bn3.toHex()) // e09bcaeda91c
console.log(bn3.toBitArray()) // binary value
console.log(bn3.toArray()) // [ 224, 155, 202, 237, 169, 28 ]

Private keys and symmetric keys are just an extension of the BigNumber class, enabling access to various specialized algorithms like digital signatures and encryption, respectively. When considering public keys, we need to go further and talk about elliptic curves and points.

Curves and Points

An elliptic curve has various properties and mathematical primitives. The curve used in Bitcoin is called secp256k1, and the SDK provides an implementation in the Curve class. In order to get started using a curve, you will need the generator point. The generator point can be multiplied with a private key in order to get a corresponding public key.

Let's start by importing the Curve class, generating a private key (a random number), and multiplying it by the generator point (called G) to get a point representing the corresponding public key:

import { Curve, BigNumber, Random } from '@bsv/sdk'

const curve = new Curve()
const privateKey = new BigNumber(Random(32))
const G = curve.g
const publicPoint = G.mul(privateKey)
console.log(`Private key: ${privateKey.toHex()}`)
// Private key: fd026136e9803295655bb342553ab8ad3260bd5e1a73ca86a7a92de81d9cee78

console.log(`Public key: ${publicPoint.toString()}`)
// Public key: 028908061925dac16b651e814995cba3dac8acbf8cf1bade40920a31a1611e6970

Now, the public key can be shared with the world, and the private key remains secure. This is because the process of point multiplication is impractical to reverse (there is no "point division" or "dividing by the generator point").

Point Addition and Multiplication

Points are represented (wrapped) at a higher level by the SDK's PublicKey class, which simply adds some extra helper functions. Conversely, the SDK wraps Big Numbers with the PrivateKey class to extend their functionality.

When dealing with points, we can perform other useful operations. For example, the type 42 scheme talks about adding one point to another. We will demonstrate, and then we'll go further to show the multiplication of a point by a number, to show the process behind ECDH:

import { Curve, BigNumber, Random } from '@bsv/sdk'

const curve = new Curve()
const G = curve.g

const key1 = new BigNumber(Random(32))
const pubpoint1 = G.mul(key1)

const key2 = new BigNumber(Random(32))
const pubpoint2 = G.mul(key2)

// two points can be added together
const added1and2 = pubpoint1.add(pubpoint2)
console.log(`${pubpoint1.toString()} + ${pubpoint2.toString()} = ${added1and2.toString()}`)
// 0280879ebda787e241ecaf27e29b0539e7a1d3895ee6c881b6e5b3c4468f379bd1 + 03ffd671622049d8f6ccb11f17dcf88fcd43d0916d9698b3d338bb9360e24d48ec = 0254b1a5132c040688f7b85a4ef56cc968c87552222d5ebeefca13f65b88790eb1

// (A * BG) = (B * AG) (this demonstrates why ECDH works)
const mul1and2 = pubpoint1.mul(key2)
console.log(`${pubpoint1.toString()} * ${key2.toHex()} = ${mul1and2.toString()}`)
const mul2and1 = pubpoint2.mul(key1)
console.log(`${pubpoint2.toString()} * ${key1.toHex()} = ${mul2and1.toString()}`)
// 0280879ebda787e241ecaf27e29b0539e7a1d3895ee6c881b6e5b3c4468f379bd1 * 695a2ce8dbf5f1889eac7a5c3711d01e3b863df8ef530b9319924a354e5c20dd = 03f3c29024e3ada33a5ea2258544c63108a8c060378dcd5a69ef69851a8a25ad1f
// 03ffd671622049d8f6ccb11f17dcf88fcd43d0916d9698b3d338bb9360e24d48ec * b329e4c294d2b04b3d6907492a0e471255d93d06472fcb2b1228d6f364c25940 = 03f3c29024e3ada33a5ea2258544c63108a8c060378dcd5a69ef69851a8a25ad1f

These lower-level constructs are useful when dealing with key derivation schemes, or when you need to perform specific mathematical operations on public, private or symmetric keys. Keep in mind that because public keys are an extension of Point, and because private and symmetric keys extend BigNumber, all of the low-level tools from these powerful base classes are always available for your use.

PreviousECDHNextSignatures

Last updated 1 year ago

Was this helpful?