Skip to content

Commit bf91de0

Browse files
authored
Merge pull request #25 from b-open-io/opl-351-docs
OPL-351 Documentation
2 parents ca4ae7c + 8572874 commit bf91de0

File tree

57 files changed

+3501
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+3501
-0
lines changed

auth/peer.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,22 @@ const AUTH_PROTOCOL_ID = "authrite message signature"
2121
// AUTH_VERSION is the version of the auth protocol
2222
const AUTH_VERSION = "0.1"
2323

24+
// OnGeneralMessageReceivedCallback is called when a general message is received from a peer.
25+
// The callback receives the sender's public key and the message payload.
2426
type OnGeneralMessageReceivedCallback func(senderPublicKey *ec.PublicKey, payload []byte) error
27+
28+
// OnCertificateReceivedCallback is called when certificates are received from a peer.
29+
// The callback receives the sender's public key and the list of certificates.
2530
type OnCertificateReceivedCallback func(senderPublicKey *ec.PublicKey, certs []*certificates.VerifiableCertificate) error
31+
32+
// OnCertificateRequestReceivedCallback is called when a certificate request is received from a peer.
33+
// The callback receives the sender's public key and the requested certificate set.
2634
type OnCertificateRequestReceivedCallback func(senderPublicKey *ec.PublicKey, requestedCertificates utils.RequestedCertificateSet) error
2735

36+
// Peer represents a peer capable of performing mutual authentication.
37+
// It manages sessions, handles authentication handshakes, certificate requests and responses,
38+
// and sending and receiving general messages over a transport layer.
39+
// This implementation supports multiple concurrent sessions per peer identity key.
2840
type Peer struct {
2941
sessionManager SessionManager
3042
transport Transport
@@ -43,6 +55,7 @@ type Peer struct {
4355
logger *log.Logger // Logger for debug messages
4456
}
4557

58+
// PeerOptions contains configuration options for creating a new Peer instance.
4659
type PeerOptions struct {
4760
Wallet wallet.Interface
4861
Transport Transport

auth/transports/simplified_http_transport.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,8 @@ func (t *SimplifiedHTTPTransport) Send(ctx context.Context, message *auth.AuthMe
142142
return nil
143143
}
144144

145+
// GetRegisteredOnData returns the first registered callback function for handling incoming AuthMessages.
146+
// Returns an error if no handlers are registered.
145147
func (t *SimplifiedHTTPTransport) GetRegisteredOnData() (func(context.Context, *auth.AuthMessage) error, error) {
146148
t.mu.Lock()
147149
defer t.mu.Unlock()

auth/transports/websocket_transport.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,15 @@ type WebSocketTransport struct {
2525
readDeadline time.Duration
2626
}
2727

28+
// WebSocketTransportOptions contains configuration options for the WebSocketTransport.
2829
type WebSocketTransportOptions struct {
2930
BaseURL string
3031
ReadDeadline int // seconds, default 30
3132
}
3233

34+
// NewWebSocketTransport creates a new WebSocket transport instance with the given options.
35+
// The BaseURL is required and must be a valid WebSocket URL.
36+
// If ReadDeadline is not specified or is zero, it defaults to 30 seconds.
3337
func NewWebSocketTransport(options *WebSocketTransportOptions) (*WebSocketTransport, error) {
3438
if options.BaseURL == "" {
3539
return nil, errors.New("BaseURL is required for WebSocket transport")

auth/types.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,8 @@ type CertificateQuery struct {
196196
Subject string
197197
}
198198

199+
// MarshalJSON customizes the JSON marshaling for AuthMessage to ensure proper formatting
200+
// of identity keys, payload, and signature fields as base64-encoded strings.
199201
func (m *AuthMessage) MarshalJSON() ([]byte, error) {
200202
type Alias AuthMessage
201203

@@ -237,6 +239,8 @@ func (m *AuthMessage) MarshalJSON() ([]byte, error) {
237239
})
238240
}
239241

242+
// UnmarshalJSON customizes the JSON unmarshaling for AuthMessage to properly decode
243+
// base64-encoded fields and reconstruct the public key from the hex-encoded identity key.
240244
func (m *AuthMessage) UnmarshalJSON(data []byte) error {
241245
type Alias AuthMessage
242246

auth/utils/get_verifiable_certificates.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ type GetVerifiableCertificatesOptions struct {
2020
PrivilegedReason string
2121
}
2222

23+
// GetVerifiableCertificates retrieves and prepares verifiable certificates based on the provided options.
24+
// It queries the wallet for certificates matching the requested types and certifiers,
25+
// then creates verifiable certificates with the appropriate fields revealed for the specified verifier.
2326
func GetVerifiableCertificates(ctx context.Context, options *GetVerifiableCertificatesOptions) ([]*certificates.VerifiableCertificate, error) {
2427
if options == nil {
2528
return nil, fmt.Errorf("GetVerifiableCertificatesOptions cannot be nil")

docs/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Go Library API Documentation
2+
3+
The documentation is split into various pages, each covering a set of related functionality. The pages are as follows:
4+
5+
- [Concepts](./concepts/) — Covers high-level concepts and architecture of the Go SDK.
6+
- [Examples](./examples/) — Provides practical examples of how to use the Go SDK.
7+
- [Low-Level](./low-level/) — Details low-level operations and functionalities within the SDK.

docs/examples/README.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,49 @@ Here, you will find a number of common usage examples for the go-sdk.
66
- [Storage Downloader](./storage_downloader/storage_downloader.md) - Download files using UHRP URLs
77
- [Storage Uploader](./storage_uploader/storage_uploader.md) - Upload, manage, and renew files
88

9+
## Keys and Addresses
10+
- [Address From WIF](./address_from_wif/) - Generate an address from a WIF private key.
11+
- [Derive Child Key](./derive_child/) - Derive a child key from a parent HD key.
12+
- [Generate HD Key](./generate_hd_key/) - Generate a new Hierarchical Deterministic (HD) key.
13+
- [HD Key From XPub](./hd_key_from_xpub/) - Create an HD key from an extended public key (xPub).
14+
- [Keyshares PK From Backup](./keyshares_pk_from_backup/) - Reconstruct a private key from key shares backup.
15+
- [Keyshares PK To Backup](./keyshares_pk_to_backup/) - Backup a private key using key shares.
16+
17+
## Transactions
18+
- [Broadcaster](./broadcaster/) - Broadcast a transaction to the network.
19+
- [Create Simple TX](./create_simple_tx/) - Create a basic Bitcoin transaction.
20+
- [Create TX With Inscription](./create_tx_with_inscription/) - Create a transaction with an Ordinal inscription.
21+
- [Create TX With OP_RETURN](./create_tx_with_op_return/) - Create a transaction with an OP_RETURN output.
22+
- [Fee Modeling](./fee_modeling/) - Examples of transaction fee calculation and modeling.
23+
- [Validate SPV](./validate_spv/) - Validate a Simple Payment Verification (SPV) proof.
24+
- [Verify Beef](./verify_beef/) - Verify a B.E.E.F (Bitcoin Extended Envelope Format) transaction.
25+
- [Verify Transaction](./verify_transaction/) - Verify the validity of a Bitcoin transaction.
26+
27+
## Messaging and Authentication
28+
- [Authenticated Messaging](./authenticated_messaging/) - Examples of authenticated messaging between parties.
29+
- [ECIES Electrum Binary](./ecies_electrum_binary/) - ECIES encryption/decryption compatible with Electrum (binary format).
30+
- [ECIES Shared](./ecies_shared/) - Elliptic Curve Integrated Encryption Scheme (ECIES) with a shared secret.
31+
- [ECIES Single](./ecies_single/) - ECIES for single recipient encryption/decryption.
32+
- [Encrypted Message](./encrypted_message/) - Send and receive encrypted messages.
33+
- [Identity Client](./identity_client/) - Client for interacting with identity services.
34+
35+
## Registry
36+
- [Registry Register](./registry_register/) - Register data with a distributed registry.
37+
- [Registry Resolve](./registry_resolve/) - Resolve data from a distributed registry.
38+
39+
## Networking
40+
- [Websocket Peer](./websocket_peer/) - Communicate with a Bitcoin node using WebSockets.
41+
42+
## Cryptography
43+
- [AES](./aes/) - Advanced Encryption Standard (AES) examples.
44+
45+
## Wallet
46+
- [Create Wallet](./create_wallet/) - Create a new wallet instance.
47+
- [Encrypt Data](./encrypt_data/) - Encrypt data using the wallet.
48+
- [Create Signature](./create_signature/) - Create a digital signature.
49+
- [Create HMAC](./create_hmac/) - Create an HMAC.
50+
- [Get Public Key](./get_public_key/) - Retrieve a public key from the wallet.
51+
- [HTTP Wallet](./http_wallet/) - Interact with a wallet using JSON over HTTP.
52+
953
## Additional Example Documents
1054
- [Converting Transactions from go-bt](./GO_BT.md)
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Address From WIF Example
2+
3+
This example demonstrates how to derive a Bitcoin SV address from a Wallet Import Format (WIF) private key string using the `ec` and `script` packages.
4+
5+
## Overview
6+
7+
The `address_from_wif` example showcases:
8+
1. Importing a private key from its WIF string representation using `ec.PrivateKeyFromWif`.
9+
2. Getting the corresponding public key from the private key using `privateKey.PubKey()`.
10+
3. Generating a P2PKH (Pay-to-Public-Key-Hash) address object from this public key using `script.NewAddressFromPublicKey`.
11+
4. Printing the serialized private key, the string representation of the derived address, and its public key hash.
12+
13+
## Code Walkthrough
14+
15+
### Deriving Address from WIF
16+
17+
```go
18+
// Import private key from WIF string
19+
privKey, _ := ec.PrivateKeyFromWif("Kxfd8ABTYZHBH3y1jToJ2AUJTMVbsNaqQsrkpo9gnnc1JXfBH8mn")
20+
21+
// Log the serialized private key (hexadecimal)
22+
log.Printf("Private key (hex): %x\n", privKey.Serialize())
23+
24+
// Get the public key associated with the private key
25+
pubKey := privKey.PubKey()
26+
27+
// Create a new address object from the public key
28+
// The 'true' argument typically indicates if it's for mainnet (compressed pubkey used for address)
29+
address, _ := script.NewAddressFromPublicKey(pubKey, true)
30+
31+
// Print the address string and the underlying public key hash
32+
fmt.Printf("Address: %s\n", address.AddressString)
33+
fmt.Printf("Public Key Hash: %s\n", address.PublicKeyHash) // Or however you wish to display the hash
34+
```
35+
36+
This section shows the step-by-step process:
37+
- `ec.PrivateKeyFromWif` parses the WIF string and returns an `*ec.PrivateKey` object.
38+
- `privKey.PubKey()` returns the corresponding `*ec.PublicKey`.
39+
- `script.NewAddressFromPublicKey(pubKey, true)` takes the public key and a boolean (often indicating network or if the key should be compressed for address generation) to produce an `*script.Address` object. This object contains the familiar base58check encoded address string and the raw public key hash.
40+
41+
## Running the Example
42+
43+
To run this example:
44+
45+
```bash
46+
go run address_from_wif.go
47+
```
48+
The output will display the hexadecimal representation of the private key, the derived P2PKH address string, and the public key hash component of the address.
49+
50+
**Note**:
51+
- The WIF string is hardcoded. In a real application, this would come from a secure source.
52+
- The example derives a P2PKH address, which is the most common address type.
53+
- The boolean argument `true` in `NewAddressFromPublicKey` typically signifies that the address should be generated for the main network, often implying the use of a compressed public key for the hash.
54+
55+
## Integration Steps
56+
57+
To derive an address from a WIF in your application:
58+
1. Obtain the WIF string for the private key.
59+
2. Use `priv, err := ec.PrivateKeyFromWif(wifString)` to get the private key object. Handle any errors.
60+
3. Get the public key: `pubKey := priv.PubKey()`.
61+
4. Generate the address: `addr, err := script.NewAddressFromPublicKey(pubKey, isMainnet)`, where `isMainnet` is true for mainnet addresses. Handle errors.
62+
5. You can then use `addr.AddressString` for display or in transactions, and `addr.PublicKeyHash` if you need the raw hash.
63+
64+
## Additional Resources
65+
66+
For more information, see:
67+
- [Package Documentation - EC primitives](https://pkg.go.dev/github.com/bsv-blockchain/go-sdk/primitives/ec)
68+
- [Package Documentation - Script](https://pkg.go.dev/github.com/bsv-blockchain/go-sdk/script)
69+
- [Generate HD Key Example](../generate_hd_key/) (for creating master keys from which WIFs can be derived)

docs/examples/aes/README.md

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# AES Encryption/Decryption Example
2+
3+
This example demonstrates basic AES (Advanced Encryption Standard) GCM (Galois/Counter Mode) encryption and decryption using the `aesgcm` package.
4+
5+
## Overview
6+
7+
The `aes` example showcases:
8+
1. Defining a hexadecimal AES key.
9+
2. Encrypting a plaintext byte slice (`[]byte("0123456789abcdef")`) using `aesgcm.AESEncrypt`.
10+
3. Decrypting the resulting ciphertext using `aesgcm.AESDecrypt` with the same key.
11+
4. Printing the decrypted data.
12+
13+
## Code Walkthrough
14+
15+
### Encrypting and Decrypting Data
16+
17+
```go
18+
package main
19+
20+
import (
21+
"encoding/hex"
22+
"fmt"
23+
24+
aes "github.com/bsv-blockchain/go-sdk/primitives/aesgcm"
25+
)
26+
27+
func main() {
28+
// Define an AES key (must be 16, 24, or 32 bytes for AES-128, AES-192, or AES-256 respectively)
29+
key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f") // 16 bytes for AES-128
30+
31+
plaintext := []byte("0123456789abcdef")
32+
33+
// Encrypt the data
34+
encryptedData, err := aes.AESEncrypt(plaintext, key)
35+
if err != nil {
36+
fmt.Println("Encryption error:", err)
37+
return
38+
}
39+
fmt.Printf("Encrypted data (hex): %x\n", encryptedData)
40+
41+
// Decrypt the data
42+
decryptedData, err := aes.AESDecrypt(encryptedData, key)
43+
if err != nil {
44+
fmt.Println("Decryption error:", err)
45+
return
46+
}
47+
fmt.Printf("Decrypted data: %s\n", decryptedData)
48+
}
49+
```
50+
51+
This section shows:
52+
- Initialization of a 16-byte AES key.
53+
- Encryption of a sample plaintext using `aes.AESEncrypt`. This function handles nonce generation and prepends it to the ciphertext.
54+
- Decryption of the ciphertext using `aes.AESDecrypt`. This function extracts the nonce from the ciphertext and performs decryption.
55+
56+
## Running the Example
57+
58+
To run this example:
59+
60+
```bash
61+
go run aes.go
62+
```
63+
The output will show the hexadecimal representation of the encrypted data, followed by the successfully decrypted original message.
64+
65+
**Note**:
66+
- The key used is hardcoded. In real applications, keys should be securely generated and managed.
67+
- The `aesgcm` package uses AES in GCM mode, which provides both confidentiality and authenticity.
68+
- The nonce is generated internally by `AESEncrypt` and prepended to the ciphertext. `AESDecrypt` expects this format.
69+
70+
## Integration Steps
71+
72+
To use AES GCM encryption/decryption in your application:
73+
74+
**For Encryption:**
75+
1. Obtain or generate a secure AES key of appropriate length (16, 24, or 32 bytes).
76+
2. Call `ciphertext, err := aesgcm.AESEncrypt(plaintextBytes, key)`.
77+
3. Store or transmit the `ciphertext`.
78+
79+
**For Decryption:**
80+
1. Obtain the same AES key used for encryption.
81+
2. Call `plaintextBytes, err := aesgcm.AESDecrypt(ciphertext, key)`.
82+
3. The `plaintextBytes` will contain the original data if decryption is successful.
83+
84+
Ensure proper key management practices are followed.
85+
86+
## Additional Resources
87+
88+
For more information, see:
89+
- [Package Documentation - aesgcm](https://pkg.go.dev/github.com/bsv-blockchain/go-sdk/primitives/aesgcm)
90+
- NIST Special Publication 800-38D for GCM mode.

0 commit comments

Comments
 (0)