certichain

Blockchain built from scratch for verifying document's legitimacy.
Log | Files | Refs | README | LICENSE

transaction.go (6276B)


      1 // Copyright 2026 Shivakumar (Certichain)
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package transaction
     16 
     17 import (
     18 	"bytes"
     19 	"cmp"
     20 	"crypto/ed25519"
     21 	"crypto/rand"
     22 	"encoding/binary"
     23 	"encoding/json"
     24 	"errors"
     25 	"fmt"
     26 	"time"
     27 
     28 	"certichain/internal/crypto"
     29 )
     30 
     31 // Transaction represents a single cryptographic anchor
     32 // on the CertiChain network.
     33 // It binds an institution's identity (DID) to a Merkle root
     34 // at a specific point in time, secured by an Ed25519 signature.
     35 type Transaction struct {
     36 	TxID       []byte `json:"tx_id"`
     37 	Nonce      []byte `json:"nonce"`
     38 	IssuerDID  string `json:"issuer_did"`
     39 	MerkleRoot []byte `json:"merkle_root"`
     40 	Timestamp  int64  `json:"timestamp"`
     41 	Signature  []byte `json:"signature,omitempty"`
     42 }
     43 
     44 // New creates a new Transaction with the given issuer DID and Merkle root.
     45 // It generates a random nonce, sets the current timestamp, and calculates the TxID.
     46 // The transaction is returned unsigned.
     47 func New(issuerDID string, merkleRoot []byte) (*Transaction, error) {
     48 	if !crypto.IsDID(issuerDID) {
     49 		return nil, errors.New("transaction: invalid or empty issuer DID")
     50 	}
     51 
     52 	if len(merkleRoot) != crypto.HashSize {
     53 		return nil, fmt.Errorf("transaction: merkle root must be exactly %d bytes", crypto.HashSize)
     54 	}
     55 
     56 	nonce := make([]byte, 32)
     57 	if _, err := rand.Read(nonce); err != nil {
     58 		return nil, fmt.Errorf("transaction: failed to generate nonce: %w", err)
     59 	}
     60 
     61 	tx := &Transaction{
     62 		Nonce:      nonce,
     63 		IssuerDID:  issuerDID,
     64 		MerkleRoot: bytes.Clone(merkleRoot),
     65 		Timestamp:  time.Now().Unix(),
     66 	}
     67 
     68 	txID, err := tx.calculateTxID()
     69 	if err != nil {
     70 		return nil, fmt.Errorf("transaction: failed to calculate txid: %w", err)
     71 	}
     72 	tx.TxID = txID
     73 
     74 	return tx, nil
     75 }
     76 
     77 // Sign generates an Ed25519 signature for the transaction
     78 // using the provided private key.
     79 //
     80 // It returns an error if the key is invalid or if the transaction
     81 // is already signed.
     82 func (tx *Transaction) Sign(privKey ed25519.PrivateKey) error {
     83 	if len(privKey) != ed25519.PrivateKeySize {
     84 		return errors.New("transaction: invalid private key size")
     85 	}
     86 	if tx.IsSigned() {
     87 		return errors.New("transaction: transaction is already signed")
     88 	}
     89 
     90 	sb, err := tx.signingBytes()
     91 	if err != nil {
     92 		return fmt.Errorf("transaction: failed to get signing bytes: %w", err)
     93 	}
     94 
     95 	tx.Signature = ed25519.Sign(privKey, sb)
     96 	return nil
     97 }
     98 
     99 // Verify validates the transaction's integrity and authenticity.
    100 // It re-calculates the TxID to ensure no fields have been tampered
    101 // with and it verifies the Ed25519 signature using the public key.
    102 func (tx *Transaction) Verify(pubKey ed25519.PublicKey) (bool, error) {
    103 	if len(pubKey) != ed25519.PublicKeySize {
    104 		return false, errors.New("transaction: invalid public key size")
    105 	}
    106 
    107 	calculatedID, err := tx.calculateTxID()
    108 	if err != nil {
    109 		return false, fmt.Errorf("transaction: verify failed: %w", err)
    110 	}
    111 
    112 	if !bytes.Equal(tx.TxID, calculatedID) {
    113 		return false, nil
    114 	}
    115 
    116 	if !tx.IsSigned() {
    117 		return false, nil
    118 	}
    119 
    120 	sb, err := tx.signingBytes()
    121 	if err != nil {
    122 		return false, fmt.Errorf("transaction: verify failed: %w", err)
    123 	}
    124 
    125 	return ed25519.Verify(pubKey, sb, tx.Signature), nil
    126 }
    127 
    128 // IsSigned returns true if the transaction contains a signature.
    129 func (tx *Transaction) IsSigned() bool {
    130 	return len(tx.Signature) > 0
    131 }
    132 
    133 // Serialize converts the transaction into a JSON byte slice for storage or transmission.
    134 func (tx *Transaction) Serialize() ([]byte, error) {
    135 	return json.Marshal(tx)
    136 }
    137 
    138 // Deserialize reconstructs a Transaction from a JSON byte slice.
    139 // Note: This function only performs structural decoding. Callers MUST call Verify()
    140 // to ensure the cryptographic integrity and authenticity of the data, especially
    141 // when deserializing transactions from untrusted sources (e.g., network, disk).
    142 func Deserialize(data []byte) (*Transaction, error) {
    143 	var tx Transaction
    144 	if err := json.Unmarshal(data, &tx); err != nil {
    145 		return nil, fmt.Errorf("transaction: deserialization failed: %w", err)
    146 	}
    147 	return &tx, nil
    148 }
    149 
    150 // Clone returns a defensive copy of the Transaction.
    151 func (tx *Transaction) Clone() *Transaction {
    152 	if tx == nil {
    153 		return nil
    154 	}
    155 	return &Transaction{
    156 		TxID:       bytes.Clone(tx.TxID),
    157 		Nonce:      bytes.Clone(tx.Nonce),
    158 		IssuerDID:  tx.IssuerDID,
    159 		MerkleRoot: bytes.Clone(tx.MerkleRoot),
    160 		Timestamp:  tx.Timestamp,
    161 		Signature:  bytes.Clone(tx.Signature),
    162 	}
    163 }
    164 
    165 // Equal compares two Transactions and returns a bool.
    166 func (tx *Transaction) Equal(other *Transaction) bool {
    167 	if tx == nil || other == nil {
    168 		return tx == other
    169 	}
    170 	return tx.IssuerDID == other.IssuerDID &&
    171 		tx.Timestamp == other.Timestamp &&
    172 		bytes.Equal(tx.TxID, other.TxID) &&
    173 		bytes.Equal(tx.Nonce, other.Nonce) &&
    174 		bytes.Equal(tx.MerkleRoot, other.MerkleRoot) &&
    175 		bytes.Equal(tx.Signature, other.Signature)
    176 }
    177 
    178 // Compare compares two Transactions for ordering.
    179 func Compare(a, b *Transaction) int {
    180 	switch {
    181 	case a == nil && b == nil:
    182 		return 0
    183 	case a == nil:
    184 		return -1
    185 	case b == nil:
    186 		return 1
    187 	}
    188 	if c := cmp.Compare(a.Timestamp, b.Timestamp); c != 0 {
    189 		return c
    190 	}
    191 	return bytes.Compare(a.TxID, b.TxID)
    192 }
    193 
    194 // calculateTxID computes the SHA-256 hash of the transaction's canonical fields.
    195 func (tx *Transaction) calculateTxID() ([]byte, error) {
    196 	sb, err := tx.signingBytes()
    197 	if err != nil {
    198 		return nil, err
    199 	}
    200 	hash := crypto.HashBytes(sb)
    201 	return hash[:], nil
    202 }
    203 
    204 // signingBytes returns a deterministic binary representation of the transaction fields
    205 // (excluding the signature) used for hashing and signing.
    206 func (tx *Transaction) signingBytes() ([]byte, error) {
    207 	timestampBytes := make([]byte, 8)
    208 	binary.BigEndian.PutUint64(timestampBytes, uint64(tx.Timestamp))
    209 
    210 	return crypto.CanonicalBytes(
    211 		tx.Nonce,
    212 		[]byte(tx.IssuerDID),
    213 		tx.MerkleRoot,
    214 		timestampBytes,
    215 	)
    216 }