@bsv/sdk 1.0.18 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,35 @@
1
+ # What is Type-42 and How Does it Enable Private Signatures?
2
+
3
+ The system known as "type-42," based on the BRC-42 technical standard introduces a sophisticated method of key derivation that enhances privacy and enables what are known as "private signatures." This document aims to elucidate the principles of type-42 derivation, demonstrate its role in enabling private signatures, and explore its broader implications within the BSV ecosystem.
4
+
5
+ ## Understanding Key Derivation
6
+
7
+ Before delving into the specifics of type-42, it is essential to understand the concept of key derivation in cryptographic systems. Key derivation is a process that generates one or more keys from a single master key, which can then be used for various cryptographic purposes, such as encryption, decryption, and digital signing. Traditional key derivation methods like BIP32 offer limited flexibility and privacy because they restrict the number of derivable keys and allow anyone to see all the derived children, even those computed by others.
8
+
9
+ ## The Type-42 Key Derivation Method
10
+
11
+ Type-42 improves upon traditional approaches by allowing two parties to independently generate a series of secret keys for each other using shared information that remains confidential between them. It improves upon BIP32 because instead of having one single public key derivation universe the entire world can see, each set of two parties who are communicating with one another share their own unique, private key derivation universe only the two of them can access. This method utilizes the following components and steps:
12
+
13
+ 1. **Identity Keys**: Each party maintains a master private key and a master public key. The whole world can know the master public key.
14
+
15
+ 2. **Shared Secret Computation**: When two parties wish to interact, sign or validate messages, they first compute a shared secret. This is achieved by one party using their private key and the other party's public key in elliptic curve point multiplication.
16
+
17
+ 3. **Key Generation Using Invoice Numbers**: To generate a unique key for a payment, message or any other purpose, the parties agree upon a specific invoice number as an identifier. An HMAC (Hash-based Message Authentication Code) is computed over this invoice number using the shared secret as the key, ensuring that each key is unique and known only to the involved parties. One party could generate the invoice number and send it to the other. Publishing the invoice number doesn't compromise security because of the HMAC.
18
+
19
+ 4. **Private and Public Key Derivation**: The HMAC output is used to derive new child keys—both private and public—ensuring that both transactional privacy and security are maintained.
20
+
21
+ ## Enabling Private Signatures with Type-42
22
+
23
+ Private signatures are a crucial application of type-42 derivation. In traditional digital signature schemes, anyone with access to the signer's public key can verify the signature. However, with Type-42:
24
+
25
+ - **Enhanced Privacy**: The signature can only be verified by someone who knows the specific shared secret used to derive the keys involved in the signature. This means that outside parties cannot verify the signature or link it back to the signer without access to the shared secret, enhancing the privacy of the exchange.
26
+
27
+ - **Security Against Replay Attacks**: Since each transaction uses a unique key derived from a different invoice number, the risk of replay attacks (where a valid data transmission is maliciously or fraudulently repeated) is minimized. This is especially true when rolling or time-based invoice numbering schemes are used.
28
+
29
+ - **Auditable by Design**: For situations requiring transparency (e.g., audits), the shared secrets or the HMAC outputs can be disclosed to specific entities, like tax agencies, without compromising the overall security of the system, or of unrelated transactions.
30
+
31
+ ## Broader Applications
32
+
33
+ Beyond private signatures, type-42 key derivation can be applied in various other contexts within BSV transactions. These include secure message exchanges, private invoicing systems, and more flexible wallet architectures that support a multitude of applications and services without compromising security or privacy.
34
+
35
+ Type-42 not only facilitates more secure and private digital signatures but also heralds a new era of cryptographic flexibility and interoperability in digital asset transactions. You can check out a tutorial leveraging the new TypeScript SDK's type-42 features [here](../examples/EXAMPLE_TYPE_42.md).
@@ -0,0 +1,38 @@
1
+ # What is BEEF and Why is it Useful?
2
+
3
+ The Background Evaluation Extended Format ([BEEF](https://github.com/bitcoin-sv/BRCs/blob/master/transactions/0062.md)) is a binary format designed for sending transactions across the Bitcoin SV (BSV) network. This document aims to demystify BEEF, outlining its structure, purpose, and the compelling advantages it offers to the BSV ecosystem.
4
+
5
+ ## Introduction to BEEF
6
+
7
+ At its core, BEEF is a protocol that encapsulates not just transactions but also their ancestry and the necessary Simplified Payment Verification (SPV) proofs. Its design is optimized for efficiency, minimizing bandwidth usage (especially when inputs have common ancestors) while maintaining the requisite data for full independent validation.
8
+
9
+ The impetus for BEEF's development arises from the need to streamline the transaction verification process without compromising on security or decentralization. Traditional SPV methods like BRC-8, while effective, have not seen widespread adoption, and BEEF aims to address this gap by providing a more uniquetous and standardized solution, aligned with the key industry stakeholders.
10
+
11
+ ## The Structure of BEEF
12
+
13
+ BEEF employs a binary stream, identified by a unique version number, to package transactions together with their Merkle proofs (BUMPs) and ancestor transactions. This bundling allows for a comprehensive verification process, starting from the most ancient transactions to the newest.
14
+
15
+ Key components of the BEEF format include:
16
+ - **Version Number**: A specific sequence that identifies the data as BEEF, allowing for future versions and improvements.
17
+ - **BUMPs**: BSV Unified Merkle Paths that prove the inclusion of transactions within the blockchain.
18
+ - **Transactions**: The actual transaction data, alongside indicators of their connection to BUMPs.
19
+
20
+ The data is arranged in a specific order to facilitate streaming validation. This means that as soon as the initial bytes (containing Merkle Paths) are received, the verification process can commence, making the validation efficient and fast.
21
+
22
+ ## Advantages of BEEF
23
+
24
+ ### Efficiency in Bandwidth Use
25
+ By condensing transactions, their ancestors, and SPV proofs into a single binary format, BEEF significantly reduces the amount of data transmitted across the network. This efficiency is crucial for scaling the BSV blockchain, making it feasible to process large volumes of transactions quickly. Thsese efficiencies compound when many inputs point back to a single common ancestor.
26
+
27
+ ### Enhanced Security and Trust
28
+ BEEF's structure ensures that every transaction can be independently verified, down to its roots in the blockchain. This process not only strengthens security but also enhances trust among network participants. Users can confidently validate transactions without relying on external sources for SPV data. By defining clear rules for validation, we ensure a lack of ambiguity among transacting parties.
29
+
30
+ ### Streamlining the Verification Process
31
+ The ordered structure of BEEF, coupled with its binary format, streamlines the verification process. Validators can begin verifying transaction ancestry as soon as they receive the data, without waiting for the entire payload. This immediate validation is particularly beneficial in complex transaction chains, where traditional methods might struggle with efficiency.
32
+
33
+ ### Future-Proofing
34
+ With its versioned format, BEEF is designed for future improvements and iterations. As the BSV ecosystem evolves, BEEF can adapt, incorporating new features or optimizations without disrupting the underlying principles that make it effective.
35
+
36
+ ## Conclusion
37
+
38
+ The Background Evaluation Extended Format represents a significant advancement in the BSV ecosystem. By combining transactions with their ancestral data and SPV proofs in a compact, binary format, BEEF addresses key challenges in transaction verification and validation. By aligning across the ecosystem, BEEF maximizes interoperability among wallets and network services. It offers a scalable, secure, and efficient mechanism for ensuring the integrity of transactions across the blockchain. You can check out an example of how to verify BEEF transactions with the TypeScript SDK [here](../examples/EXAMPLE_VERIFYING_BEEF.md).
@@ -0,0 +1,38 @@
1
+ # The Role of Chain Trackers within the SPV Ecosystem
2
+
3
+ ## Introduction
4
+
5
+ Simplified Payment Verification (SPV) is a method that allows participants in the BSV network to verify transactions without needing the full blockchain. This process is crucial for enhancing scalability and efficiency, particularly now that the daily transaction volume has become substantial. Chain trackers play a vital role within this SPV ecosystem, ensuring the integrity and reliability of this transaction verification process by managing and verifying blockchain headers and checking Merkle roots.
6
+
7
+ ## Conceptual Overview of SPV
8
+
9
+ The SPV process was originally proposed to allow anyone to verify transactions without requiring the complete blockchain data. Instead of storing the entire ledger, people only need to maintain a copy of the block headers. The essential components of SPV include:
10
+
11
+ - **Block Headers**: Clients store headers of all blocks instead of full blocks, significantly reducing the data storage requirement.
12
+ - **Merkle Proofs**: These proofs allow the verification of the inclusion of a transaction within a block without needing the entire block's content.
13
+
14
+ ## Role of Chain Trackers
15
+
16
+ A chain tracker is a specialized component within the SPV architecture responsible for maintaining and updating a consistent and accurate view of the blockchain header chain. Its functions include:
17
+
18
+ - **Header Discovery and Verification**: Chain trackers continuously discover new block headers propagated through the network. They verify each header's integrity by checking the correctness of the proof-of-work and ensuring it correctly references the previous header.
19
+
20
+ - **Merkle Root Verification**: Once a new block header is accepted, the chain tracker validates Merkle roots presented in transaction proofs against the expected Merkle root in the block header. This step is crucial for ensuring that the transaction was indeed included in the block.
21
+
22
+ - **Chain Reorganizations**: In cases where the blockchain undergoes a reorganization (a rare occurrence), chain trackers adjust their header chain accordingly. They ensure that the client's view of the block sequence is always aligned with the honest chain, as recognized by the network.
23
+
24
+ ### Security and Trust
25
+
26
+ Chain trackers significantly enhance the security of SPV clients by enabling them to trust the validity of transactions while relying on minimal blockchain data. They help in mitigating risks such as double-spending and blockchain forks by ensuring clients are always synchronized with the correct network state.
27
+
28
+ ### Scalability Contributions
29
+
30
+ By enabling everyone on the network to verify transactions without full blockchain data, chain trackers contribute directly to the scalability of BSV. They allow more users to participate in the network without compromising on security or requiring extensive resources for full-chain indexing, thus supporting broader adoption and use at lower cost.
31
+
32
+ ## Chain Trackers in Action
33
+
34
+ To illustrate the role of chain trackers, consider a scenario where an SPV client receives a transaction with a Merkle proof. The chain tracker checks the transaction's Merkle root against a stored block header. If the root matches, the transaction is confirmed to be part of the chain, thereby verifying its inclusion without needing the entire associated block's data.
35
+
36
+ ## Conclusion
37
+
38
+ Chain trackers are indispensable in the SPV ecosystem, providing a balance between efficiency and security. By managing blockchain headers and verifying Merkle proofs, they ensure that participants can trust and validate transactions with confidence. Their role is foundational in enabling scalable, secure, and efficient transaction verification across the network. You can see a tutorial on integrating a chain tracker with the TypeScript BSV SDK [here](../examples/EXAMPLE_VERIFYING_ROOTS.md).
@@ -0,0 +1,35 @@
1
+ ## How Does Transaction Fee Modeling Work?
2
+
3
+ Fees provide the incentive for miners to process and include transactions in the blockchain. This document provides a high-level conceptual overview of how transaction fee modeling works within the BSV ecosystem, highlighting its impact on both miners and network participants.
4
+
5
+ ### Why Transaction Fees?
6
+
7
+ Transaction fees are paid by users to miners, who validate and add transactions to new blocks. Fees not only compensate miners for their computational power but also help secure the network by driving investments into higher scalability and more efficient transaction processing. This mechanism ensures that miners prioritize transactions with higher fees, thus aligning the users' needs with the miners' efforts.
8
+
9
+ ### How Fees Are Calculated
10
+
11
+ #### Basic Fee Calculation
12
+
13
+ Currently, the most common metric for calculating transaction fees is based on the size of the transaction in kilobytes (KB). The fee model typically employed is the "satoshis per kilobyte" model, which assigns a certain number of satoshis (the smallest unit of Bitcoin) per kilobyte of transaction data. This model is straightforward: it multiplies the transaction size by a predetermined satoshi rate to determine the total fee.
14
+
15
+ #### Factors Influencing Fees
16
+
17
+ Different fee models may be used to evaluate the priority for transactions by transaction processors. Some factors that could be considered include:
18
+
19
+ 1. **Transaction Size**: The primary factor affecting the fee is the transaction size, which includes the data such present in input and output scripts. Larger transactions require more bandwidth and processing power to validate, and thus generally incur higher fees.
20
+
21
+ 2. **Number of Inputs and Outputs**: Transactions with many inputs that reduce the size of the UTXO set might be processed for les, while transactions that create lots of outputs and increase the UTXO set size might be more expensive.
22
+
23
+ 3. **Script Complexity**: Transactions that use complex scripts or multiple signature verifications require more processing power, potentially increasing the fee.
24
+
25
+ ### Advanced Fee Models
26
+
27
+ While the satoshis per kilobyte model is predominant, there are opportunities within the BSV ecosystem to implement more sophisticated fee strategies, especially in contexts where particular script templates are commonly used:
28
+
29
+ - **Fee Discounts for Priority Transactions**: Offer discounted rates for transactions that consolidate UTXOs or batch multiple outputs, which can improve the overall efficiency of the blockchain.
30
+
31
+ - **Custom Fee Models**: Some applications might implement custom fee models tailored to their specific needs, such as microtransactions in online games or high-volume, automated payments in smart contracts.
32
+
33
+ ### Implementing Custom Fee Models
34
+
35
+ The BSV SDK allows developers to create and use custom fee models. These models can consider various factors beyond simple transaction size, enabling a flexible approach to transaction fee calculation. For instance, you can see a tutorial building a custom fee model [here](../examples/EXAMPLE_FEE_MODELING.md).
@@ -0,0 +1,19 @@
1
+ # What are Hashes and Why are they Important in Bitcoin?
2
+
3
+ #### What is a Hash?
4
+
5
+ In the context of computer science, a hash is a function that converts an input (or 'message') into a fixed-size string of bytes. The output, typically a 'digest', represents concisely the original input data. A hash function is a type of one-way function, meaning it's easy to compute a hash from a given input but nearly impossible to recreate the original input just by knowing the hash value. This property ensures data integrity, as any alteration of the input data will result in a dramatically different hash.
6
+
7
+ #### Chain of Headers Using Hashes
8
+
9
+ In Bitcoin, every block in the blockchain is linked to its predecessor through a series of hash pointers in what is known as the 'chain of headers'. Each block header contains its own hash along with the hash of the previous block's header. This structure forms a secure, verifiable chain where each subsequent block reinforces the security of the previous block. Altering any single block would require recomputation of every hash that follows, a task computationally impractical, thus ensuring the integrity of the blockchain.
10
+
11
+ #### Merkle Trees: Verifying Transaction Inclusion
12
+
13
+ One of the core components of Bitcoin’s architecture is the use of Merkle trees as referenced in the Bitcoin whitepaper under sections 7 & 8. This efficient data structure allows us to quickly verify the inclusion of transactions in a block. Each transaction within a block has its hash, and these hashes are paired, hashed, paired again, and re-hashed until a single hash remains: the Merkle Root, which is stored in the block header. This process allows for a quick and secure verification of whether a specific transaction is included in the block without needing to download every transaction.
14
+
15
+ #### Practical Applications: On-Chain Use Cases and Tamper Evidence
16
+
17
+ The real-world application of hashing within applications built upon the Bitcoin SV blockchain is vast, particularly when proving the integrity and authenticity of data. For instance, in legal, financial, or real estate transactions, proving the non-tampered nature of a document or a series of transactions can be critical. Here, Bitcoin's blockchain serves as a tamper-evident ledger. Once data has been recorded in a block and absorbed into the blockchain through the chaining of hashes and the Merkle Root, it becomes immutable. This immutability is a powerful tool for proving that a document or transaction has not been altered post its original timestamping on the blockchain.
18
+
19
+ If there needs to be an added level of privacy, while also insuring that there is an immutable record, the data itself can also be hashed prior to being recorded on chain. This allows anyone to check that the hash of the data matches without having to reveal what that data is to the world.
@@ -0,0 +1,60 @@
1
+ # How are Transactions Built with Inputs and Outputs?
2
+
3
+ Transactions are the fundamental entities within the blockchain, acting as the mechanism through which value is transferred across the network. Understanding how transactions are built using inputs and outputs is crucial for developers, as this process encompasses the core of creating, signing, and sending transactions within applications.
4
+
5
+ ## Understanding Transactions
6
+
7
+ A **transaction** in BSV is a record that transfers some outputs containing Bitcoins from one state to the next. However, unlike traditional banking systems, these transactions aren't direct debits or credits to an account. Instead, they reference outputs created by previous transactions as thrir inputs and create new outputs as future spendable coins.
8
+
9
+ ### Transaction Structure
10
+
11
+ Each transaction consists of the following components:
12
+
13
+ - **Version**: Indicates the ruleset under which the transaction is validated, or which overlay network(s) it belongs to.
14
+ - **Inputs**: List of references to outputs from previous transactions, showing where the bitcoins being sent were previously stored.
15
+ - **Outputs**: List of allocations of bitcoins, specifying the amount and conditions under which they can be spent in the future.
16
+ - **Lock Time**: An optional setting that specifies the earliest time or block number at which the transaction can be valid.
17
+
18
+ Transactions can also be attached to a **Merkle proof** to provide proof of inclusion in a particular block, after they have been processed.
19
+
20
+ ## Inputs and Outputs
21
+
22
+ Inputs and outputs are the essential elements that make up a transaction. Understanding their structure and usage is key to mastering transaction creation and manipulation using the BSV SDK.
23
+
24
+ ### Transaction Inputs
25
+
26
+ A **Transaction Input** includes the following fields:
27
+
28
+ - **Source Transaction ID**: The transaction ID (TXID) from which the input bitcoins are derived.
29
+ - **Source Output Index**: Specifies which output from the referenced transaction is to be spent.
30
+ - **Unlocking Script**: Contains signatures or other unlocking solutions that prove the right to spend the referenced previous output.
31
+ - **Sequence**: A number that can be used to allow transaction inputs to be updated before finalization, if it's less than 0xFFFFFFFF.
32
+
33
+ Inputs connect a new transaction back to the point in the blockchain where the bitcoins were previously recorded as outputs.
34
+
35
+ ### Transaction Outputs
36
+
37
+ A **Transaction Output** consists of:
38
+
39
+ - **Satoshis**: The amount of BSV being transferred.
40
+ - **Locking Script**: Defines the conditions under which the output can be spent, such as requiring a digital signature from the recipient's public key.
41
+
42
+ Outputs create spendable coins that can be used as inputs in future transactions.
43
+
44
+ ## Constructing a Transaction
45
+
46
+ Creating a transaction involves several clear steps, utilizing inputs and outputs to dictate where bitcoins are moving from and to:
47
+
48
+ 1. **Define Outputs**: Decide the amount of BSV to transfer and the conditions under which the transfer can later be spent.
49
+ 2. **Select Inputs**: Identify previous transaction outputs to spend that have enough balance to cover the outputs and the transaction fee.
50
+ 3. **Calculate Fees**: Estimate the necessary transaction fee based on transaction size, where you will be broadcasting, and the level of service priority you require.
51
+ 4. **Generate Change**: If inputs exceed the sum of outputs and fees, create change output(s) sending the excess back to the sender without re-using keys.
52
+ 5. **Unlock Inputs**: Utilize the private keys or other mechanisms associated with the inputs you're spending to unlock each one, thereby authorizing the bitcoins to be spent.
53
+ 6. **Complete Unlocking**: In cases of multi-party transactions, pass the transaction around to all needed parties for unlocking.
54
+ 7. **Broadcast**: Send the final signed transaction to the BSV network for inclusion in a block, and register it with overlay networks as required.
55
+
56
+ Each of these steps is facilitated by the BSV SDK, which provides comprehensive tools and templates to handle the complexities of transaction creation, from generating cryptographic signatures to managing network broadcast clients.
57
+
58
+ ## Conclusion
59
+
60
+ The BSV SDK empowers developers to build robust applications on the network by abstracting the complexities of transaction creation. By understanding how transactions are structured and built through inputs and outputs, developers can leverage the full potential of the BSV blockchain, ensuring secure, efficient, and scalable applications. You can check out an example of creating transactions [in this tutorial!](../examples/EXAMPLE_COMPLEX_TX.md)
@@ -0,0 +1,38 @@
1
+ # Opcodes and Their Functionality Within Bitcoin Script
2
+
3
+ ## Introduction
4
+ BSV is underpinned by a powerful scripting language that plays a crucial role in securing transactions. This language, which defines the conditions under which coins can be spent, relies heavily on "opcodes" — operational codes that manipulate and evaluate data. This document aims to demystify the functionality of these opcodes, providing examples of their use.
5
+
6
+ ## Securing Coins with Script Predicates
7
+ Scripts secure coins through predicates. A predicate is essentially a condition that must be met for coins to be spent. In Bitcoin, these conditions are defined using a scripting language that determines how and when the coins can be transferred. The scripts ensure that only the rightful owner of the coins can spend them by satisfying the conditions laid down in the script attached to each coin or output.
8
+
9
+ ## Script Execution Environment: Stacks and Scripts
10
+ Bitcoin's scripting system operates in a stack-based execution environment. This means that the script processes data using two primary structures:
11
+ - **Main stack:** Where most operations are performed.
12
+ - **Alt stack:** Used occasionally to provide additional stack flexibility.
13
+
14
+ Scripts in Bitcoin are divided into two parts:
15
+ 1. **Unlocking script:** Provided by the spender of the coins, this script supplies the data needed to satisfy the conditions of the locking script.
16
+ 2. **Locking script:** Placed by the recipient in a transaction output, this script sets the conditions under which the coins can be spent.
17
+
18
+ The execution begins with the unlocking script, which places data on the stack. Following this, the locking script is appended and continues to operate on the same stack. The spend is considered valid if, at the end of execution, the top of the stack holds a "true" value (non-zero).
19
+
20
+ ## Understanding Opcodes
21
+ Opcodes are the operational codes used within a script to perform specific functions on the data in the stacks. Each opcode manipulates stack data to perform operations such as addition, subtraction, logical comparisons, cryptographic hashes, signature checks, and more. After executing an opcode, the results are pushed back onto the stack, altering its state for subsequent operations.
22
+
23
+ ### Examples of Common Opcodes
24
+ - **OP_ADD:** Pops the top two items off the stack, adds them, and pushes the result back onto the stack.
25
+ - **OP_EQUAL:** Pops the top two items, compares them, and pushes `1` (true) if they are equal, or `0` (false) otherwise.
26
+ - **OP_HASH256:** Pops the top item, computes its double SHA-256 hash, and pushes the result back onto the stack.
27
+ - **OP_CHECKSIG:** Pops a public key and a signature from the stack and checks if the signature is valid for the given public key and wider transaction; pushes `1` if the signature is valid.
28
+
29
+ These opcodes are foundational for enabling complex scripting capabilities in BSV, allowing for the creation of various types of transactions including multi-signature wallets, escrow arrangements, sCrypt smart contracts, and much more.
30
+
31
+ ## Combining Opcodes to Secure Coins
32
+ The true power of scripting comes from the combination of opcodes to form complex predicates. These predicates secure the coins by requiring that certain conditions be met before the coins can be spent. For example, a script might require that a transaction be signed by multiple parties (multi-signature), or that a certain amount of time elapse before the coins can be spent (timelocks).
33
+
34
+ ### Implementing Cryptographic Primitives
35
+ Opcodes also implement various cryptographic primitives such as digital signatures and hashing. These primitives are essential for maintaining the security and integrity of transactions on the blockchain. For instance, the `OP_CHECKSIG` opcode is crucial for verifying that a transaction is authorized by the holder of the private keys associated with the coins being spent.
36
+
37
+ ## Conclusion
38
+ By understanding the functionality of opcodes within the Bitcoin scripting language, users and developers can appreciate the flexibility and security that Bitcoin scripts provide. You can check out [this example](../examples/EXAMPLE_VERIFYING_SPENDS.md) of how to validate spends within the BSV SDK.
@@ -0,0 +1,14 @@
1
+ # Conceptual Topics
2
+
3
+ These documents cover high-level conceptual information that will augment developers' understanding of the code-level SDK documentation:
4
+
5
+ - [What is BEEF and why is it useful?](BEEF.md)
6
+ - [What is a Transaction Signature?](TX_SIG.md)
7
+ - [What is Type-42 and How Does it Enable Private Signatures?](./42.md)
8
+ - [What are Script Templates Used for?](TEMPLATES.md)
9
+ - [How are Transactions Built with Inputs and Outputs?](HOW_TX.md)
10
+ - [The Role of Chain Trackers within the SPV Ecosystem](CHAIN_SPV.md)
11
+ - [How Does Transaction Fee Modeling Work?](FEE.md)
12
+ - [How are Bitcoin Transactions Validated?](TX_VALID.md)
13
+ - [Opcodes and Their Functionality Within Bitcoin Script](OP.md)
14
+ - [What are Hashes and Why are they Important in Bitcoin?](HASHES.md)
@@ -0,0 +1,42 @@
1
+ # What are Script Templates Used for?
2
+
3
+ Script templates play a critical role in facilitating the creation and management of scripts that control the locking and unlocking of UTXOs (transaction outputs or tokens in BSV). These scripts are integral to implementing the various transaction protocols on the blockchain, adhering to Bitcoin's original vision while enhancing security, scalability, and efficiency.
4
+
5
+ ## The Role of Scripts in BSV
6
+
7
+ Scripts are pieces of code that define the conditions under which funds can be spent on the blockchain. Every transaction on the BSV network includes two kinds of scripts:
8
+ - **Locking Scripts**: These scripts set conditions under which coins can be spent. They are included in the output of a transaction.
9
+ - **Unlocking Scripts**: These scripts satisfy the conditions set by the locking scripts to spend the funds in a subsequent transaction. They are found in the input of a transaction.
10
+
11
+ The purpose of these scripts is to ensure that only authorized parties can access and transact the funds by meeting predefined conditions, which may include providing a digital signature or solving a computational challenge. Any conceivable set of constraints can be programmed into a locking script.
12
+
13
+ ## Concept of Script Templates
14
+
15
+ A script template is a predefined framework that simplifies the process of creating otherwise-potentially-complex locking and unlocking scripts. It abstracts away the underlying script construction details, allowing developers to create scripts without having to write low-level code for every new scenario. The template provides methods and properties to generate scripts dynamically based on the transaction context and the specific input parameters provided.
16
+
17
+ ### Components of a Script Template
18
+ A script template generally includes the following:
19
+
20
+ 1. **Lock Method**: This method generates a locking script based on given parameters, such as a public key hash or other conditions defined by the transaction type (e.g., P2PKH—Pay to Public Key Hash).
21
+
22
+ 2. **Unlock Method**: This method creates an unlocking script, which usually involves generating a digital signature and potentially other data required to unlock the funds according to the locking script's conditions.
23
+
24
+ 3. **Estimate Length**: This utility provides an estimation of the unlocking script's length, which can be crucial for transaction fee calculation.
25
+
26
+ ## Importance of Script Templates
27
+
28
+ ### Simplification and Standardization
29
+ Script templates standardize the creation of scripts, ensuring consistency and reducing errors in script generation. They provide a high-level interface for commonly used script patterns, like P2PKH, reducing the need for repetitive, error-prone coding.
30
+
31
+ ### Security Enhancements
32
+ By abstracting the details of script creation, script templates help in minimizing security risks associated with manual script handling. Robust templates can ensure that scripts are generated in a secure manner, adhering to the necessary cryptographic standards and best practices. Templates can also be audited for increased security, which will benefit everyone who relies upon it.
33
+
34
+ ### Scalability and Efficiency
35
+ Script templates enable developers to quickly implement and deploy blockchain solutions on a large scale. They reduce the complexity involved in script creation, allowing developers to focus on building applications rather than dealing with the intricacies of script coding.
36
+
37
+ ### Flexibility
38
+ Templates are designed to be flexible and extensible, accommodating various transaction types and conditions without significant modifications to the underlying codebase. This flexibility is crucial for adapting to evolving use cases and requirements in the BSV ecosystem.
39
+
40
+ ## Conclusion
41
+
42
+ Script templates are fundamental tools within the BSV SDK that streamline the development of on-chain use-cases by providing robust, secure, and efficient methods for handling transaction scripts. They encapsulate the complexity of script creation and ensure that developers can focus on higher-level application logic, thereby accelerating the development process and enhancing the capabilities of their implementations. To get started with script templates in the TypeScript SDK, [check out this tutorial!](../examples/EXAMPLE_SCRIPT_TEMPLATES.md)
@@ -0,0 +1,34 @@
1
+ # What are Transaction Signatures?
2
+
3
+ Transaction signatures play a crucial role in securing transactions and establishing trust between parties. These digital signatures serve as a powerful tool for validating the authenticity and integrity of spends on the blockchain. This document delves into the concept of transaction signatures, breaking down their components, functionality, and significance in a way that's (hopefully) accessible to a fairly broad audience.
4
+
5
+ ## Introduction to Digital Signatures
6
+
7
+ Before diving into transaction signatures, it's essential to understand the basics of digital signatures. A digital signature is akin to a fingerprint; it is a unique mark that an individual can use to sign digital documents or transactions. Just as a handwritten signature authenticates the identity of the signer and their consent to the document's terms, a digital signature ensures that a digital document or transaction is authentic and hasn't been tampered with after the signature was made.
8
+
9
+ ## Components of Transaction Signatures
10
+
11
+ Transaction signatures in BSV are a special type of digital signature. They consist of several key components:
12
+
13
+ - **r and s values**: These two values constitute the core of the ECDSA (Elliptic Curve Digital Signature Algorithm) signature. They are derived from the private key of the sender and the transaction data. Together, they verify that the owner of the corresponding public key has authorized the transaction.
14
+ - **SIGHASH flags**: Transaction signatures also include SIGHASH flags, which specify how much of the transaction data is covered by the signature. These flags allow signers to control which parts of the transaction they are committing to when they sign it, and which ones might be updated later.
15
+
16
+ ## Understanding SIGHASH Flags
17
+
18
+ SIGHASH flags provide flexibility in how transactions are signed, offering several options:
19
+
20
+ - **SIGHASH_ALL**: This is the default mode, where the signature covers all the inputs and outputs of the transaction. It indicates the signer's commitment to the exact details of the transaction, including the amount and script associated with each output.
21
+ - **SIGHASH_NONE**: With this flag, the signature covers all inputs but no outputs, allowing others to add or modify outputs. This could be used in scenarios where the signer is indifferent to where the funds are going.
22
+ - **SIGHASH_SINGLE**: This mode signs only one input and one output, the one with the same index as the signed input. It is useful for transactions with multiple participants, allowing each to sign only for their part.
23
+ - **SIGHASH_ANYONECANPAY**: This flag can be combined with the others and indicates that the signature covers only the current input, allowing others to add more inputs to the transaction.
24
+
25
+ ## The Role of Transaction Signatures
26
+
27
+ Transaction signatures serve two primary purposes on the BSV network:
28
+
29
+ 1. **Authentication**: By signing a transaction with their private key, the sender proves they hold the private keys needed by the locking script that secures the funds they're attempting to spend.
30
+ 2. **Integrity**: Once a transaction is signed, any alteration to the parts that were signed would invalidate the signature. This property ensures that once a transaction is broadcasted to the network, it cannot be tampered with or altered by malicious actors.
31
+
32
+ ## Conclusion
33
+
34
+ Transaction signatures are at the heart of the security and trust model of blockchain technology. They enable the secure transfer of digital assets between parties without the need for a central authority. By understanding the components and functionality of transaction signatures, users and developers can better appreciate the sophisticated mechanisms that keep the BSV network secure and trustworthy. You can learn more about how transaction signatures work within the TypeScript BSV SDK [here](../low-level/TX_SIG.md).
@@ -0,0 +1,35 @@
1
+ # How are Bitcoin Transactions Validated?
2
+
3
+ Understanding the intricacies of Bitcoin transaction validation is crucial for developers building systems that receive and process them within the ecosystem. This document will delve into the foundational concepts surrounding Bitcoin transactions, peer-to-peer exchange, and Simplified Payment Verification (SPV), as well as the critical validation processes that underpin the BSV network's scaling model.
4
+
5
+ ## Introduction
6
+
7
+ Bitcoin transactions are the lifeblood of the network, enabling the transfer of value between participants without the need for central intermediaries. Each transaction on the Bitcoin SV blockchain is verified through a series of cryptographic checks and balances that ensure its authenticity and compliance with network rules.
8
+
9
+ ### Key Concepts
10
+
11
+ - **Transactions:** These are data structures that encode the transfer of value between participants in the network.
12
+ - **Peer-to-Peer Exchange:** Direct interaction between participants' wallets without the need for a central authority, in which transactions and associated merkle proofs are sent back and forth.
13
+ - **SPV (Simplified Payment Verification):** A method for validating transactions that does not require downloading the entire blockchain, facilitating more scalable applications.
14
+
15
+ ## The Transaction Validation Process
16
+
17
+ Validating a Bitcoin transaction involves several critical steps that confirm its legitimacy and adherence to the rules set by the network. Here's a breakdown of the validation process:
18
+
19
+ 1. **Script Execution:**
20
+ - Each input in a transaction has an unlocking script that must successfully execute and validate against the locking script of the output it is spending.
21
+ - The result of this script execution must be true, indicating that the conditions to spend the output are met.
22
+
23
+ 2. **Transaction Outputs vs. Inputs:**
24
+ - The total value of outputs must not exceed the total value of inputs, ensuring that no new money is created out of thin air, except for the coinbase transaction, which includes the block reward.
25
+ - Check that the transaction includes enough fee to be included in a block, as miners prioritize transactions with higher fees.
26
+
27
+ 3. **Merkle Path Verifications:**
28
+ - Each input must be traceable back to a transaction included in a block, verified through a Merkle path.
29
+ - This ensures that each input used is legitimate and recognized by the network as having been previously confirmed.
30
+
31
+ 4. **Checking Locktime and Sequence:**
32
+ - Transactions may include locktime and sequence numbers that impose conditions on the earliest time or block height at which a transaction can be added to the blockchain.
33
+ - Proper handling of these parameters ensures that transactions are processed in a timely and orderly manner.
34
+
35
+ You can check out an example using the TypeScript SDK where a transaction is verified according to these rules [here](../examples/EXAMPLE_VERIFYING_BEEF.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/sdk",
3
- "version": "1.0.18",
3
+ "version": "1.0.19",
4
4
  "type": "module",
5
5
  "description": "BSV Blockchain Software Development Kit",
6
6
  "main": "dist/cjs/mod.js",
@@ -282,8 +282,8 @@ export default class Signature {
282
282
  compactByte += 4
283
283
  }
284
284
  let arr = [compactByte]
285
- arr = arr.concat(this.r.toArray())
286
- arr = arr.concat(this.s.toArray())
285
+ arr = arr.concat(this.r.toArray('be', 32))
286
+ arr = arr.concat(this.s.toArray('be', 32))
287
287
  if (enc === 'hex') {
288
288
  return toHex(arr)
289
289
  } else if (enc === 'base64') {