### Handle IPNS Errors in Go Source: https://context7.com/ipfs/go-ipns/llms.txt This example demonstrates how to create IPNS records with intentional errors and use the go-ipns validation functions to identify specific failure conditions such as expired records or invalid signatures. It relies on the go-libp2p crypto package for key generation and the ipns package for record creation and validation. The output lists detected errors and prints common IPNS error constants. ```go package main import ( "errors" "fmt" "time" "github.com/ipfs/go-ipns" "github.com/libp2p/go-libp2p/core/crypto" ) func main() { privateKey, public _ := crypto.GenerateKeyPair(crypto.RSA, 2048) ipfsPath := []byte("/ipfs/QmErrorTest") // Test expired record error pastTime := time.Now().Add(-1 * time.Hour) expiredRecord, _ := ipns.Create(privateKey, ipfsPath, 0, pastTime, 0) err := ipns.Validate(publicKey, expiredRecord) if errors.Is(err, ipns.ErrExpiredRecord) { fmt.Println("Detected ErrExpiredRecord: record has expired") } // Test signature error with wrong key _, wrongKey, _ := crypto.GenerateKeyPair(crypto.RSA, 2048) validRecord, _ := ipns.Create(privateKey, ipfsPath, 0, time.Now().Add(1*time.Hour), 0) err = ipns.Validate(wrongKey, validRecord) if errors.Is(err, ipns.ErrSignature) { fmt.Println("Detected ErrSignature: signature verification failed") } // Other common errors fmt.Println("\nCommon IPNS errors:") fmt.Printf(" ErrInvalidPath: %v\n", ipns.ErrInvalidPath) fmt.Printf(" ErrKeyFormat: %v\n", ipns.ErrKeyFormat) fmt.Printf(" ErrPublicKeyNotFound: %v\n", ipns.ErrPublicKeyNotFound) fmt.Printf(" ErrPublicKeyMismatch: %v\n", ipns.ErrPublicKeyMismatch) fmt.Printf(" ErrBadRecord: %v\n", ipns.ErrBadRecord) fmt.Printf(" ErrRecordSize: %v (max: %d bytes)\n", ipns.ErrRecordSize, ipns.MaxRecordSize) fmt.Printf(" ErrUnrecognizedValidity: %v\n", ipns.ErrUnrecognizedValidity) } ``` -------------------------------- ### Create IPNS record in Go Source: https://context7.com/ipfs/go-ipns/llms.txt Creates a new cryptographically signed IPNS record that points to an IPFS path with a specified expiration time and sequence number. Requires RSA key pair generation and uses the go-ipns and go-libp2p libraries. The example demonstrates creating a record that expires in one hour. ```go package main import ( "fmt" "time" "github.com/ipfs/go-ipns" "github.com/libp2p/go-libp2p/core/crypto" ) func main() { // Generate RSA key pair for signing privateKey, publicKey, err := crypto.GenerateKeyPair(crypto.RSA, 2048) if err != nil { panic(fmt.Errorf("failed to generate key pair: %w", err)) } // IPFS content path to point to ipfsPath := []byte("/ipfs/Qme1knMqwt1hKZbc1BmQFmnm9f36nyQGwXxPGVpVJ9rMK5") // Create record with sequence 0, expires in 1 hour, no TTL eol := time.Now().Add(1 * time.Hour) record, err := ipns.Create(privateKey, ipfsPath, 0, eol, 0) if err != nil { panic(fmt.Errorf("failed to create IPNS record: %w", err)) } fmt.Printf("Created IPNS record:\n") fmt.Printf(" Value: %s\n", string(record.Value)) fmt.Printf(" Sequence: %d\n", record.GetSequence()) fmt.Printf(" Validity: %s\n", string(record.Validity)) fmt.Printf(" Has SignatureV2: %v\n", record.SignatureV2 != nil) } ``` -------------------------------- ### Generate IPNS Key Pairs using Go Source: https://context7.com/ipfs/go-ipns/llms.txt This snippet shows how to generate RSA and Ed25519 key pairs with the go-ipns examples package, extract the corresponding peer IDs, and display key metadata. It depends on the go-libp2p core peer package and requires no external input beyond the key size for RSA. The code outputs the generated keys' peer IDs and types, useful for publishing IPNS records. ```go package main import ( "fmt" "github.com/ipfs/go-ipns/examples" "github.com/libp2p/go-libp2p/core/peer" ) func main() { // Generate RSA key pair (2048 bits) rsaPrivKey, err := examples.GenerateRSAKeyPair(2048) if err != nil { panic(fmt.Errorf("failed to generate RSA key: %w", err)) } rsaPubKey := rsaPrivKey.GetPublic() rsaPeerID, _ := peer.IDFromPublicKey(rsaPubKey) fmt.Printf("Generated RSA key pair\n") fmt.Printf(" Peer ID: %s\n", rsaPeerID.String()) fmt.Printf(" Key type: %s\n", rsaPrivKey.Type()) // Generate Ed25519 key pair ed25519PrivKey, err := examples.GenerateEDKeyPair() if err != nil { panic(fmt.Errorf("failed to generate Ed25519 key: %w", err)) } ed25519PubKey := ed25519PrivKey.GetPublic() ed25519PeerID, _ := peer.IDFromPublicKey(ed25519PubKey) fmt.Printf("\nGenerated Ed25519 key pair\n") fmt.Printf(" Peer ID: %s\n", ed25519PeerID.String()) fmt.Printf(" Key type: %s\n", ed25519PrivKey.Type()) // Note: Ed25519 public keys can be extracted from peer ID extractedKey, err := ed25519PeerID.ExtractPublicKey() if err == nil { fmt.Println(" Ed25519 public key can be extracted from peer ID") } else { fmt.Println(" Public key cannot be extracted from peer ID") } } ``` -------------------------------- ### Validate IPNS record in Go Source: https://context7.com/ipfs/go-ipns/llms.txt Validates an IPNS record by verifying its cryptographic signature, checking expiration time, and ensuring data integrity. Uses the go-ipns and go-libp2p libraries. The example shows validation of both valid and expired records, demonstrating error handling for expired records. ```go package main import ( "fmt" "time" "github.com/ipfs/go-ipns" pb "github.com/ipfs/go-ipns/pb" "github.com/libp2p/go-libp2p/core/crypto" ) func main() { // Create a test record privateKey, publicKey, _ := crypto.GenerateKeyPair(crypto.RSA, 2048) ipfsPath := []byte("/ipfs/QmTest123") eol := time.Now().Add(24 * time.Hour) record, _ := ipns.Create(privateKey, ipfsPath, 0, eol, 0) // Validate the record err := ipns.Validate(publicKey, record) if err != nil { fmt.Printf("Validation failed: %v\n", err) return } fmt.Println("Record validation successful") // Test with expired record expiredEol := time.Now().Add(-1 * time.Hour) expiredRecord, _ := ipns.Create(privateKey, ipfsPath, 1, expiredEol, 0) err = ipns.Validate(publicKey, expiredRecord) if err == ipns.ErrExpiredRecord { fmt.Println("Correctly detected expired record") } } ``` -------------------------------- ### Embed and extract public key in Go Source: https://context7.com/ipfs/go-ipns/llms.txt Embeds a public key in an IPNS record for validation by nodes that cannot derive the key from the peer ID. Requires RSA key pair generation and uses the go-ipns and go-libp2p libraries. The example demonstrates embedding a public key in a record and then extracting and verifying it. ```go package main import ( "fmt" "time" "github.com/ipfs/go-ipns" "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" ) func main() { // Generate RSA key pair (RSA keys cannot be extracted from peer ID) privateKey, publicKey, err := crypto.GenerateKeyPair(crypto.RSA, 2048) if err != nil { panic(err) } peerID, _ := peer.IDFromPublicKey(publicKey) // Create IPNS record ipfsPath := []byte("/ipfs/QmExample") eol := time.Now().Add(48 * time.Hour) record, _ := ipns.Create(privateKey, ipfsPath, 0, eol, 0) // Embed public key in record err = ipns.EmbedPublicKey(publicKey, record) if err != nil { panic(fmt.Errorf("failed to embed public key: %w", err)) } fmt.Printf("Embedded public key in record (size: %d bytes)\n", len(record.PubKey)) // Extract public key from record extractedKey, err := ipns.ExtractPublicKey(peerID, record) if err != nil { panic(fmt.Errorf("failed to extract public key: %w", err)) } // Verify extracted key matches original extractedPeerID, _ := peer.IDFromPublicKey(extractedKey) if extractedPeerID == peerID { fmt.Println("Successfully extracted and verified public key") } } ``` -------------------------------- ### Compare IPNS Records in Go Source: https://context7.com/ipfs/go-ipns/llms.txt This code demonstrates comparing two IPNS records to determine which is newer based on sequence number and validity timestamp. It uses the go-ipns library to create records and perform comparisons, outputting results for different scenarios. The function handles sequence-based ordering and expiration time differences, assuming valid crypto keys and paths. ```go package main import ( "fmt" "time" "github.com/ipfs/go-ipns" "github.com/libp2p/go-libp2p/core/crypto" ) func main() { privateKey, _, _ := crypto.GenerateKeyPair(crypto.RSA, 2048) ipfsPath := []byte("/ipfs/QmTest") // Create two records with different sequences record1, _ := ipns.Create(privateKey, ipfsPath, 0, time.Now().Add(1*time.Hour), 0) record2, _ := ipns.Create(privateKey, ipfsPath, 1, time.Now().Add(1*time.Hour), 0) result, err := ipns.Compare(record1, record2) if err != nil { panic(fmt.Errorf("comparison failed: %w", err)) } switch result { case -1: fmt.Println("Record 1 is older than Record 2") case 0: fmt.Println("Records cannot be ordered") case 1: fmt.Println("Record 1 is newer than Record 2") } // Compare with different validity times but same sequence futureEol := time.Now().Add(48 * time.Hour) record3, _ := ipns.Create(privateKey, ipfsPath, 1, futureEol, 0) result, _ = ipns.Compare(record2, record3) if result == -1 { fmt.Println("Record with later expiration is considered newer") } } ``` -------------------------------- ### Validate IPNS Records with libp2p in Go Source: https://context7.com/ipfs/go-ipns/llms.txt This snippet implements a libp2p record validator for IPNS records, validating them using a keybook for distributed systems. It creates records, embeds public keys, serializes them, and performs validation and selection of the best record. Dependencies include go-ipns and libp2p libraries. ```go package main import ( "fmt" "time" "github.com/gogo/protobuf/proto" "github.com/ipfs/go-ipns" pb "github.com/ipfs/go-ipns/pb" "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/peerstore" ) func main() { // Generate key pair and peer ID privateKey, publicKey, _ := crypto.GenerateKeyPair(crypto.RSA, 2048) peerID, _ := peer.IDFromPublicKey(publicKey) // Create and embed public key in record ipfsPath := []byte("/ipfs/QmValidatorExample") eol := time.Now().Add(24 * time.Hour) record, _ := ipns.Create(privateKey, ipfsPath, 0, eol, 0) ipns.EmbedPublicKey(publicKey, record) // Serialize record recordBytes, _ := proto.Marshal(record) // Create validator with keybook keybook := peerstore.NewKeyBook() keybook.AddPubKey(peerID, publicKey) validator := ipns.Validator{KeyBook: keybook} // Validate using the key format /ipns/{peerID} key := ipns.RecordKey(peerID) err := validator.Validate(key, recordBytes) if err != nil { fmt.Printf("Validation failed: %v\n", err) return } fmt.Printf("Record validated successfully for key: %s\n", key) // Test record selection (choosing best record from multiple) record2, _ := ipns.Create(privateKey, ipfsPath, 1, eol, 0) ipns.EmbedPublicKey(publicKey, record2) record2Bytes, _ := proto.Marshal(record2) bestIndex, err := validator.Select(key, [][]byte{recordBytes, record2Bytes}) if err != nil { panic(err) } fmt.Printf("Best record is at index: %d (should be 1 due to higher sequence)\n", bestIndex) } ``` -------------------------------- ### Create IPNS Record in Go Source: https://github.com/ipfs/go-ipns/blob/master/README.md Generates an IPNS record pointing to a given IPFS content identifier, signed with a provided private key and set to expire at a specified time. It requires the `go-ipns` and `go-libp2p-crypto` packages. The output is an IPNS record suitable for publishing. ```go import ( time "time" ipns "github.com/ipfs/go-ipns" crypto "github.com/libp2p/go-libp2p-crypto" ) // Generate a private key to sign the IPNS record with. Most of the time, // however, you'll want to retrieve an already-existing key from IPFS using the // go-ipfs/core/coreapi CoreAPI.KeyAPI() interface. privateKey, publicKey, err := crypto.GenerateKeyPair(crypto.RSA, 2048) if err != nil { panic(err) } // Create an IPNS record that expires in one hour and points to the IPFS address // /ipfs/Qme1knMqwt1hKZbc1BmQFmnm9f36nyQGwXxPGVpVJ9rMK5 ipnsRecord, err := ipns.Create(privateKey, []byte("/ipfs/Qme1knMqwt1hKZbc1BmQFmnm9f36nyQGwXxPGVpVJ9rMK5"), 0, time.Now().Add(1*time.Hour)) if err != nil { panic(err) } ``` -------------------------------- ### Retrieve EOL Timestamp from IPNS Record in Go Source: https://context7.com/ipfs/go-ipns/llms.txt This code retrieves the end-of-life (EOL) timestamp from an IPNS record for making TTL and caching decisions. It creates a record with a set expiration and extracts the timestamp, then checks if it's still valid. Inputs are the record and outputs the timestamp, with limitations on time handling. ```go package main import ( "fmt" "time" "github.com/ipfs/go-ipns" "github.com/libp2p/go-libp2p/core/crypto" ) func main() { privateKey, _, _ := crypto.GenerateKeyPair(crypto.RSA, 2048) ipfsPath := []byte("/ipfs/QmEOLTest") // Create record expiring in 6 hours expirationTime := time.Now().Add(6 * time.Hour) record, _ := ipns.Create(privateKey, ipfsPath, 0, expirationTime, 0) // Retrieve EOL from record eol, err := ipns.GetEOL(record) if err != nil { panic(fmt.Errorf("failed to get EOL: %w", err)) } fmt.Printf("Record expires at: %s\n", eol.Format(time.RFC3339)) fmt.Printf("Time until expiration: %s\n", time.Until(eol).Round(time.Minute)) // Check if record is still valid if time.Now().Before(eol) { fmt.Println("Record is still valid") } else { fmt.Println("Record has expired") } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.