commit 51d116ead12acb209476193bcfc1610ee7b60122
parent 8186527a6b08d906a2803ca4d21d6f379cbbd5c9
Author: Shivakumar <[email protected]>
Date: Sun, 24 May 2026 13:51:57 +0530
feat(transaction): add transaction and unit tests
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
2 files changed, 557 insertions(+), 0 deletions(-)
diff --git a/internal/transaction/transaction.go b/internal/transaction/transaction.go
@@ -0,0 +1,171 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package transaction
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "certichain/internal/crypto"
+)
+
+// Transaction represents a single cryptographic anchor
+// on the CertiChain network.
+// It binds an institution's identity (DID) to a Merkle root
+// at a specific point in time, secured by an Ed25519 signature.
+type Transaction struct {
+ TxID []byte `json:"tx_id"`
+ Nonce []byte `json:"nonce"`
+ IssuerDID string `json:"issuer_did"`
+ MerkleRoot []byte `json:"merkle_root"`
+ Timestamp int64 `json:"timestamp"`
+ Signature []byte `json:"signature,omitempty"`
+}
+
+// New creates a new Transaction with the given issuer DID and Merkle root.
+// It generates a random nonce, sets the current timestamp, and calculates the TxID.
+// The transaction is returned unsigned.
+func New(issuerDID string, merkleRoot []byte) (*Transaction, error) {
+ if !crypto.IsDID(issuerDID) {
+ return nil, errors.New("transaction: invalid or empty issuer DID")
+ }
+
+ if len(merkleRoot) != crypto.HashSize {
+ return nil, fmt.Errorf("transaction: merkle root must be exactly %d bytes", crypto.HashSize)
+ }
+
+ nonce := make([]byte, 32)
+ if _, err := rand.Read(nonce); err != nil {
+ return nil, fmt.Errorf("transaction: failed to generate nonce: %w", err)
+ }
+
+ tx := &Transaction{
+ Nonce: nonce,
+ IssuerDID: issuerDID,
+ MerkleRoot: bytes.Clone(merkleRoot),
+ Timestamp: time.Now().Unix(),
+ }
+
+ txID, err := tx.calculateTxID()
+ if err != nil {
+ return nil, fmt.Errorf("transaction: failed to calculate txid: %w", err)
+ }
+ tx.TxID = txID
+
+ return tx, nil
+}
+
+// Sign generates an Ed25519 signature for the transaction
+// using the provided private key.
+//
+// It returns an error if the key is invalid or if the transaction
+// is already signed.
+func (tx *Transaction) Sign(privKey ed25519.PrivateKey) error {
+ if len(privKey) != ed25519.PrivateKeySize {
+ return errors.New("transaction: invalid private key size")
+ }
+ if tx.IsSigned() {
+ return errors.New("transaction: transaction is already signed")
+ }
+
+ sb, err := tx.signingBytes()
+ if err != nil {
+ return fmt.Errorf("transaction: failed to get signing bytes: %w", err)
+ }
+
+ tx.Signature = ed25519.Sign(privKey, sb)
+ return nil
+}
+
+// Verify validates the transaction's integrity and authenticity.
+// It re-calculates the TxID to ensure no fields have been tampered
+// with and it verifies the Ed25519 signature using the public key.
+func (tx *Transaction) Verify(pubKey ed25519.PublicKey) (bool, error) {
+ if len(pubKey) != ed25519.PublicKeySize {
+ return false, errors.New("transaction: invalid public key size")
+ }
+
+ calculatedID, err := tx.calculateTxID()
+ if err != nil {
+ return false, fmt.Errorf("transaction: verify failed: %w", err)
+ }
+
+ if !bytes.Equal(tx.TxID, calculatedID) {
+ return false, nil
+ }
+
+ if !tx.IsSigned() {
+ return false, nil
+ }
+
+ sb, err := tx.signingBytes()
+ if err != nil {
+ return false, fmt.Errorf("transaction: verify failed: %w", err)
+ }
+
+ return ed25519.Verify(pubKey, sb, tx.Signature), nil
+}
+
+// IsSigned returns true if the transaction contains a signature.
+func (tx *Transaction) IsSigned() bool {
+ return len(tx.Signature) > 0
+}
+
+// Serialize converts the transaction into a JSON byte slice for storage or transmission.
+func (tx *Transaction) Serialize() ([]byte, error) {
+ return json.Marshal(tx)
+}
+
+// Deserialize reconstructs a Transaction from a JSON byte slice.
+// Note: This function only performs structural decoding. Callers MUST call Verify()
+// to ensure the cryptographic integrity and authenticity of the data, especially
+// when deserializing transactions from untrusted sources (e.g., network, disk).
+func Deserialize(data []byte) (*Transaction, error) {
+ var tx Transaction
+ if err := json.Unmarshal(data, &tx); err != nil {
+ return nil, fmt.Errorf("transaction: deserialization failed: %w", err)
+ }
+ return &tx, nil
+}
+
+// calculateTxID computes the SHA-256 hash of the transaction's canonical fields.
+func (tx *Transaction) calculateTxID() ([]byte, error) {
+ sb, err := tx.signingBytes()
+ if err != nil {
+ return nil, err
+ }
+ hash := crypto.HashBytes(sb)
+ return hash[:], nil
+}
+
+// signingBytes returns a deterministic binary representation of the transaction fields
+// (excluding the signature) used for hashing and signing.
+func (tx *Transaction) signingBytes() ([]byte, error) {
+ timestampBytes := make([]byte, 8)
+ binary.BigEndian.PutUint64(timestampBytes, uint64(tx.Timestamp))
+
+ return crypto.CanonicalBytes(
+ tx.Nonce,
+ []byte(tx.IssuerDID),
+ tx.MerkleRoot,
+ timestampBytes,
+ )
+}
diff --git a/internal/transaction/transaction_test.go b/internal/transaction/transaction_test.go
@@ -0,0 +1,386 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package transaction
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/hex"
+ "testing"
+
+ "certichain/internal/crypto"
+)
+
+// TestTransactionLifecycle validates the standard "happy path" of a transaction:
+// creation, signing, verification, and serialization/deserialization.
+func TestTransactionLifecycle(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ pub, priv, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key: %v", err)
+ }
+
+ // Generate a valid DID
+ issuer, err := crypto.NewDID(pub)
+ if err != nil {
+ t.Fatalf("failed to generate DID: %v", err)
+ }
+
+ // Create a dummy Merkle root.
+ root := make([]byte, 32)
+ for i := range root {
+ root[i] = byte(i)
+ }
+
+ // Test Creation
+ tx, err := New(issuer, root)
+ if err != nil {
+ t.Fatalf("New() failed: %v", err)
+ }
+
+ if tx.IssuerDID != issuer {
+ t.Errorf("expected issuer %s, got %s", issuer, tx.IssuerDID)
+ }
+ if !bytes.Equal(tx.MerkleRoot, root) {
+ t.Errorf("merkle root mismatch")
+ }
+ if len(tx.TxID) != 32 {
+ t.Errorf("invalid TxID length: %d", len(tx.TxID))
+ }
+ if tx.IsSigned() {
+ t.Errorf("transaction should not be signed yet")
+ }
+
+ // Test Signing
+ err = tx.Sign(priv)
+ if err != nil {
+ t.Fatalf("Sign() failed: %v", err)
+ }
+ if !tx.IsSigned() {
+ t.Errorf("transaction should be signed")
+ }
+
+ // Test Verification
+ valid, err := tx.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if !valid {
+ t.Errorf("Verify() returned false for valid transaction")
+ }
+
+ // Test Serialization
+ data, err := tx.Serialize()
+ if err != nil {
+ t.Fatalf("Serialize() failed: %v", err)
+ }
+
+ tx2, err := Deserialize(data)
+ if err != nil {
+ t.Fatalf("Deserialize() failed: %v", err)
+ }
+
+ // Verify that the restored transaction matches the original.
+ if !bytes.Equal(tx.TxID, tx2.TxID) {
+ t.Errorf("TxID mismatch after serialization")
+ }
+ if !bytes.Equal(tx.Signature, tx2.Signature) {
+ t.Errorf("Signature mismatch after serialization")
+ }
+
+ // Final verification of the deserialized transaction.
+ valid2, err := tx2.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() on deserialized tx failed: %v", err)
+ }
+ if !valid2 {
+ t.Errorf("Verify() returned false for deserialized transaction")
+ }
+}
+
+// TestTransactionTampering ensures that any modification to a signed transaction's
+// fields results in a verification failure. Each subtest uses a fresh transaction
+// to avoid shared mutable state issues.
+func TestTransactionTampering(t *testing.T) {
+ t.Parallel()
+
+ // Helper to create a signed transaction for tampering tests.
+ setup := func(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey, string, *Transaction) {
+ t.Helper()
+ pub, priv, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key: %v", err)
+ }
+ issuer, err := crypto.NewDID(pub)
+ if err != nil {
+ t.Fatalf("failed to generate DID: %v", err)
+ }
+ root := make([]byte, 32)
+ tx, err := New(issuer, root)
+ if err != nil {
+ t.Fatalf("New() failed: %v", err)
+ }
+ if err := tx.Sign(priv); err != nil {
+ t.Fatalf("Sign() failed: %v", err)
+ }
+ return pub, priv, issuer, tx
+ }
+
+ t.Run("TamperMerkleRoot", func(t *testing.T) {
+ t.Parallel()
+ pub, _, _, tx := setup(t)
+ tx.MerkleRoot[0] ^= 0xFF
+ valid, err := tx.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if valid {
+ t.Errorf("Verify() should fail for tampered MerkleRoot")
+ }
+ })
+
+ t.Run("TamperIssuer", func(t *testing.T) {
+ t.Parallel()
+ pub, _, _, tx := setup(t)
+
+ otherPub, _, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key: %v", err)
+ }
+ otherDID, err := crypto.NewDID(otherPub)
+ if err != nil {
+ t.Fatalf("failed to generate DID: %v", err)
+ }
+ tx.IssuerDID = otherDID
+
+ valid, err := tx.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if valid {
+ t.Errorf("Verify() should fail for tampered IssuerDID")
+ }
+ })
+
+ t.Run("TamperNonce", func(t *testing.T) {
+ t.Parallel()
+ pub, _, _, tx := setup(t)
+ tx.Nonce[0] ^= 0xFF
+ valid, err := tx.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if valid {
+ t.Errorf("Verify() should fail for tampered Nonce")
+ }
+ })
+
+ t.Run("TamperTimestamp", func(t *testing.T) {
+ t.Parallel()
+ pub, _, _, tx := setup(t)
+ tx.Timestamp += 1
+ valid, err := tx.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if valid {
+ t.Errorf("Verify() should fail for tampered Timestamp")
+ }
+ })
+
+ t.Run("TamperSignature", func(t *testing.T) {
+ t.Parallel()
+ pub, _, _, tx := setup(t)
+ tx.Signature[0] ^= 0xFF
+ valid, err := tx.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if valid {
+ t.Errorf("Verify() should fail for tampered Signature")
+ }
+ })
+}
+
+// TestInvalidInputs verifies the sanitization logic in the New() constructor.
+func TestInvalidInputs(t *testing.T) {
+ t.Parallel()
+
+ t.Run("EmptyIssuer", func(t *testing.T) {
+ t.Parallel()
+ _, err := New("", make([]byte, 32))
+ if err == nil {
+ t.Error("expected error for empty issuer")
+ }
+ })
+
+ t.Run("InvalidDIDFormat", func(t *testing.T) {
+ t.Parallel()
+ _, err := New("invalid-did", make([]byte, 32))
+ if err == nil {
+ t.Error("expected error for invalid DID format")
+ }
+ })
+
+ t.Run("InvalidDIDLength", func(t *testing.T) {
+ t.Parallel()
+ shortHash := hex.EncodeToString(make([]byte, 31))
+ _, err := New(crypto.DIDPrefix+shortHash, make([]byte, 32))
+ if err == nil {
+ t.Error("expected error for short DID hash")
+ }
+ })
+
+ t.Run("InvalidMerkleRootSize", func(t *testing.T) {
+ t.Parallel()
+ _, err := New("did:certchain:0x"+hex.EncodeToString(make([]byte, 32)), make([]byte, 31))
+ if err == nil {
+ t.Error("expected error for invalid merkle root size")
+ }
+ })
+}
+
+// TestNonceUniqueness verifies that two transactions created with the same inputs
+// have different nonces and therefore different TxIDs, providing replay protection.
+func TestNonceUniqueness(t *testing.T) {
+ t.Parallel()
+
+ pub, _, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key: %v", err)
+ }
+ issuer, err := crypto.NewDID(pub)
+ if err != nil {
+ t.Fatalf("failed to generate DID: %v", err)
+ }
+ root := make([]byte, 32)
+
+ tx1, err := New(issuer, root)
+ if err != nil {
+ t.Fatalf("New() 1 failed: %v", err)
+ }
+
+ tx2, err := New(issuer, root)
+ if err != nil {
+ t.Fatalf("New() 2 failed: %v", err)
+ }
+
+ if bytes.Equal(tx1.Nonce, tx2.Nonce) {
+ t.Error("nonces should be unique")
+ }
+ if bytes.Equal(tx1.TxID, tx2.TxID) {
+ t.Error("TxIDs should be unique")
+ }
+}
+
+// TestDoubleSignGuard verifies that Sign() cannot be called twice on the same transaction.
+func TestDoubleSignGuard(t *testing.T) {
+ t.Parallel()
+
+ pub, priv, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key: %v", err)
+ }
+ issuer, err := crypto.NewDID(pub)
+ if err != nil {
+ t.Fatalf("failed to generate DID: %v", err)
+ }
+ tx, err := New(issuer, make([]byte, 32))
+ if err != nil {
+ t.Fatalf("New() failed: %v", err)
+ }
+
+ if err := tx.Sign(priv); err != nil {
+ t.Fatalf("first Sign() failed: %v", err)
+ }
+
+ if err := tx.Sign(priv); err == nil {
+ t.Error("expected error on second Sign() call")
+ }
+}
+
+// TestVerify_WrongKey verifies that a valid signed transaction returns false (and no error)
+// when verified against a different public key.
+func TestVerify_WrongKey(t *testing.T) {
+ t.Parallel()
+
+ pubA, privA, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key A: %v", err)
+ }
+ issuerA, err := crypto.NewDID(pubA)
+ if err != nil {
+ t.Fatalf("failed to generate DID A: %v", err)
+ }
+
+ pubB, _, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key B: %v", err)
+ }
+
+ tx, err := New(issuerA, make([]byte, 32))
+ if err != nil {
+ t.Fatalf("New() failed: %v", err)
+ }
+ if err := tx.Sign(privA); err != nil {
+ t.Fatalf("Sign() failed: %v", err)
+ }
+
+ valid, err := tx.Verify(pubB)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if valid {
+ t.Error("Verify() should return false when using the wrong public key")
+ }
+}
+
+// TestVerifyUnsigned verifies that Verify() returns false for a transaction that hasn't been signed.
+func TestVerifyUnsigned(t *testing.T) {
+ t.Parallel()
+
+ pub, _, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate key: %v", err)
+ }
+ issuer, err := crypto.NewDID(pub)
+ if err != nil {
+ t.Fatalf("failed to generate DID: %v", err)
+ }
+ tx, err := New(issuer, make([]byte, 32))
+ if err != nil {
+ t.Fatalf("New() failed: %v", err)
+ }
+
+ valid, err := tx.Verify(pub)
+ if err != nil {
+ t.Fatalf("Verify() errored: %v", err)
+ }
+ if valid {
+ t.Error("Verify() should return false for unsigned transaction")
+ }
+}
+
+// TestDeserializeInvalidJSON verifies that Deserialize() returns an error for malformed JSON.
+func TestDeserializeInvalidJSON(t *testing.T) {
+ t.Parallel()
+
+ _, err := Deserialize([]byte(`{invalid json`))
+ if err == nil {
+ t.Error("expected error for invalid JSON")
+ }
+}