# Transaction Format

## Overview

QuantumWing transactions use **Dilithium Mode 3 signatures** (3293 bytes) with **EVM-compatible addresses** (0x...).

{% hint style="success" %}
**Compatibility**: EVM address format | **Security**: Quantum-safe Dilithium signatures | **Size**: \~3.5 KB per tx
{% endhint %}

## Transaction Structure

### Standard Transaction

```go
type Transaction struct {
    // Header fields
    Nonce    uint64   // Account nonce (prevents replay)
    GasPrice uint64   // Gas price in gwei
    GasLimit uint64   // Max gas to consume
    To       Address  // Recipient address (20 bytes)
    Value    *big.Int // Amount in wei
    Data     []byte   // Contract call data or empty
    
    // Quantum-safe signature fields
    DilithiumSignature []byte // 3293 bytes (Mode 3)
    DilithiumPublicKey []byte // 1952 bytes (Mode 3)
    
    // Derived fields (computed from signature)
    From Address // Sender address (derived from pubkey)
    Hash Hash    // Transaction hash (SHA3-256)
}
```

### Size Comparison

| Field          | QuantumWing      | Ethereum          |
| -------------- | ---------------- | ----------------- |
| **Header**     | \~100 bytes      | \~100 bytes       |
| **Signature**  | 3293 bytes       | 65 bytes          |
| **Public Key** | 1952 bytes       | 0 bytes (derived) |
| **Total**      | **\~5345 bytes** | **\~165 bytes**   |
| **Overhead**   | **32x larger**   | Baseline          |

{% hint style="info" %}
**Mitigation**: Signature aggregation planned for Q1 2026 will reduce tx size by \~90%.
{% endhint %}

## Transaction Types

### 1. **Simple Transfer**

Transfer ETH from one account to another.

```json
{
  "nonce": 42,
  "gasPrice": 20000000000,
  "gasLimit": 21000,
  "to": "0x1234567890abcdef1234567890abcdef12345678",
  "value": "1000000000000000000",
  "data": ""
}
```

**Gas Cost**: 21,000 gas (same as Ethereum)

### 2. **Contract Deployment**

Deploy a new smart contract (QWVM).

```json
{
  "nonce": 43,
  "gasPrice": 20000000000,
  "gasLimit": 1000000,
  "to": null,
  "value": "0",
  "data": "0x608060405234801561001057600080fd5b50..."
}
```

**Gas Cost**: 32,000 + contract\_size \* 200

### 3. **Contract Call**

Execute a contract method.

```json
{
  "nonce": 44,
  "gasPrice": 20000000000,
  "gasLimit": 100000,
  "to": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5",
  "value": "0",
  "data": "0xa9059cbb000000000000000000000000..."
}
```

**Gas Cost**: 21,000 + execution\_cost

## Signing Process

### Step 1: Create Unsigned Transaction

```go
import "github.com/quantumwing/protocol/blockchain/evm"

tx := &evm.Transaction{
    Nonce:    42,
    GasPrice: 20_000_000_000, // 20 gwei
    GasLimit: 21_000,
    To:       common.HexToAddress("0x1234567890abcdef1234567890abcdef12345678"),
    Value:    big.NewInt(1_000_000_000_000_000_000), // 1 ETH
    Data:     []byte{},
}
```

### Step 2: Serialize Transaction

Uses **SSZ (Simple Serialize)** encoding for deterministic hashing:

```go
import "github.com/quantumwing/protocol/blockchain/types/ssz"

// Serialize transaction
sszEncoded := ssz.Marshal(tx)

// Hash with SHA3-256
txHash := sha3.Sum256(sszEncoded)
```

**SSZ Benefits**:

* ✅ Deterministic (same input → same output)
* ✅ Fast encoding/decoding
* ✅ Merkleization support
* ✅ Used by Ethereum 2.0

### Step 3: Sign with Dilithium

```go
import "github.com/open-quantum-safe/liboqs-go/oqs"

// Initialize Dilithium signer
signer := oqs.Signature{}
defer signer.Clean()
signer.Init("Dilithium3", privateKey)

// Sign transaction hash
signature, err := signer.Sign(txHash[:])
if err != nil {
    return err
}

// Attach signature to transaction
tx.DilithiumSignature = signature       // 3293 bytes
tx.DilithiumPublicKey = publicKey       // 1952 bytes
```

### Step 4: Derive Sender Address

```go
// Derive EVM address from Dilithium public key
senderAddress := crypto.DilithiumToAddress(publicKey)
tx.From = senderAddress

// Compute final transaction hash
tx.Hash = sha3.Sum256(ssz.Marshal(tx))
```

### Complete Example

```go
package main

import (
    "fmt"
    "math/big"
    
    "github.com/quantumwing/protocol/blockchain/evm"
    "github.com/quantumwing/protocol/crypto/dilithium"
)

func main() {
    // 1. Load wallet
    wallet, err := dilithium.LoadWallet("wallet.json", "password")
    if err != nil {
        panic(err)
    }
    
    // 2. Create transaction
    tx := &evm.Transaction{
        Nonce:    wallet.GetNonce(),
        GasPrice: 20_000_000_000,
        GasLimit: 21_000,
        To:       common.HexToAddress("0x1234567890abcdef1234567890abcdef12345678"),
        Value:    big.NewInt(1_000_000_000_000_000_000),
        Data:     []byte{},
    }
    
    // 3. Sign transaction
    signedTx, err := wallet.SignTransaction(tx)
    if err != nil {
        panic(err)
    }
    
    // 4. Send to network
    hash, err := rpcClient.SendTransaction(signedTx)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Transaction sent: %s\n", hash.Hex())
}
```

## Transaction Hash Calculation

### Formula

```
TxHash = SHA3-256(SSZ(Transaction))
```

### SSZ Encoding Order

```
SSZ Root:
├─ Nonce (uint64)
├─ GasPrice (uint64)
├─ GasLimit (uint64)
├─ To (20 bytes)
├─ Value (32 bytes, big-endian)
├─ Data (variable length)
├─ DilithiumSignature (3293 bytes)
└─ DilithiumPublicKey (1952 bytes)
```

### Example

```go
// Transaction fields
tx := Transaction{
    Nonce:    42,
    GasPrice: 20_000_000_000,
    GasLimit: 21_000,
    To:       common.HexToAddress("0x1234567890abcdef1234567890abcdef12345678"),
    Value:    big.NewInt(1_000_000_000_000_000_000),
    Data:     []byte{},
    DilithiumSignature: signature,  // 3293 bytes
    DilithiumPublicKey: publicKey,  // 1952 bytes
}

// Compute hash
sszBytes := ssz.Marshal(tx)
txHash := sha3.Sum256(sszBytes)

fmt.Printf("Transaction Hash: 0x%x\n", txHash)
// Output: 0xabcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab
```

## Address Derivation

### From Dilithium Public Key → 0x Address

```go
func DilithiumToAddress(publicKey []byte) Address {
    // 1. Hash Dilithium public key (1952 bytes)
    hash := sha3.Sum256(publicKey)
    
    // 2. Take last 20 bytes
    address := hash[12:32]
    
    // 3. Return as 0x-prefixed hex
    return Address(address)
}
```

### Example

```
Dilithium Public Key (1952 bytes):
0x9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f...

SHA3-256 Hash:
0x000000000000000000000000742d35Cc6634C0532925a3b844Bc9e7595f0bEb5

EVM Address (last 20 bytes):
0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5 ✅
```

## Nonce Management

### Sequential Nonces

Each account has a **nonce counter** starting at 0:

```go
// First transaction: nonce = 0
tx1 := &Transaction{Nonce: 0, ...}

// Second transaction: nonce = 1
tx2 := &Transaction{Nonce: 1, ...}

// Third transaction: nonce = 2
tx3 := &Transaction{Nonce: 2, ...}
```

{% hint style="danger" %}
**Critical**: Nonces must be sequential! If nonce 5 is sent before nonce 4, tx will be **rejected**.
{% endhint %}

### Get Current Nonce

```bash
curl -X POST http://localhost:8546 \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_getTransactionCount",
    "params": ["0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5", "latest"],
    "id": 1
  }'
```

**Response**:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x2a"  // Nonce = 42
}
```

### Handling Nonce Gaps

If transaction fails, **reuse the same nonce**:

```go
// Transaction failed
tx1 := &Transaction{Nonce: 42, GasPrice: 10, ...}
// Status: Failed (insufficient gas)

// Resubmit with higher gas price
tx2 := &Transaction{Nonce: 42, GasPrice: 20, ...}  // Same nonce!
// Status: Success ✅
```

## Gas & Fees

### Gas Price

**Current**: 20 gwei (0.00000002 ETH) **Recommended**: Check `eth_gasPrice` API

```bash
curl -X POST http://localhost:8546 \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_gasPrice",
    "params": [],
    "id": 1
  }'
```

### Gas Limit

| Operation               | Gas Cost           |
| ----------------------- | ------------------ |
| **Simple Transfer**     | 21,000             |
| **Contract Deployment** | 32,000 + data      |
| **Contract Call**       | 21,000 + execution |
| **Storage Write**       | 20,000 per slot    |
| **Dilithium Verify**    | 50,000             |

### Total Fee Calculation

```
Total Fee = Gas Used × Gas Price

Example:
├─ Gas Used: 21,000
├─ Gas Price: 20 gwei
└─ Total Fee: 21,000 × 20 = 420,000 gwei = 0.00042 ETH
```

## Transaction Lifecycle

```mermaid
graph TD
    A[Create Transaction] --> B[Sign with Dilithium]
    B --> C[Submit to Mempool]
    C --> D{Valid?}
    D -->|No| E[Reject]
    D -->|Yes| F[Pending State]
    
    F --> G[Validator Selects Tx]
    G --> H[Include in Block Proposal]
    H --> I[Block Propagates]
    I --> J[Beacon Verifies Signatures]
    J --> K{Valid Block?}
    
    K -->|No| L[Orphan Block]
    K -->|Yes| M[Execution Layer Processes]
    M --> N{Execution Success?}
    
    N -->|No| O[Tx Failed, Gas Consumed]
    N -->|Yes| P[Tx Success, State Updated]
    
    O --> Q[Receipt: status=0]
    P --> R[Receipt: status=1]
    
    R --> S[Wait 64 Slots]
    S --> T[Finalized ✅]
```

### States

1. **Created** - Transaction signed locally
2. **Pending** - In mempool, waiting for inclusion
3. **Included** - In proposed block
4. **Confirmed** - Block accepted by network
5. **Finalized** - Irreversible (after 64 slots)

## Validation Rules

### Pre-Execution Checks

```go
func ValidateTransaction(tx *Transaction) error {
    // 1. Check signature
    if !dilithium.Verify(tx.Hash, tx.DilithiumSignature, tx.DilithiumPublicKey) {
        return ErrInvalidSignature
    }
    
    // 2. Verify sender address
    derivedAddr := crypto.DilithiumToAddress(tx.DilithiumPublicKey)
    if derivedAddr != tx.From {
        return ErrInvalidSender
    }
    
    // 3. Check nonce
    expectedNonce := state.GetNonce(tx.From)
    if tx.Nonce != expectedNonce {
        return ErrInvalidNonce
    }
    
    // 4. Check balance
    balance := state.GetBalance(tx.From)
    totalCost := tx.Value + (tx.GasLimit * tx.GasPrice)
    if balance < totalCost {
        return ErrInsufficientFunds
    }
    
    // 5. Check gas limit
    if tx.GasLimit < 21000 {
        return ErrGasTooLow
    }
    if tx.GasLimit > 40_000_000 {
        return ErrGasTooHigh
    }
    
    return nil
}
```

### Post-Execution Checks

```go
func FinalizeTransaction(tx *Transaction, receipt *Receipt) {
    // 1. Deduct gas fee
    gasFee := receipt.GasUsed * tx.GasPrice
    state.SubBalance(tx.From, gasFee)
    state.AddBalance(block.Proposer, gasFee)  // Reward proposer
    
    // 2. Increment nonce
    state.SetNonce(tx.From, tx.Nonce + 1)
    
    // 3. Transfer value (if success)
    if receipt.Status == 1 {
        state.SubBalance(tx.From, tx.Value)
        state.AddBalance(tx.To, tx.Value)
    }
}
```

## CLI Usage

### Send Transaction

```bash
quantum-wing wallet send \
  --from wallet.json \
  --to 0x1234567890abcdef1234567890abcdef12345678 \
  --amount 1.5 \
  --gas-price 20 \
  --gas-limit 21000 \
  --rpc http://localhost:8546
```

### Check Transaction Status

```bash
quantum-wing tx status \
  --hash 0xabcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab \
  --rpc http://localhost:8546
```

### Get Receipt

```bash
quantum-wing tx receipt \
  --hash 0xabcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab \
  --rpc http://localhost:8546
```

## Further Reading

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>✍️ Signing Process</strong></td><td>Deep dive into Dilithium signing</td><td><a href="https://github.com/dolfrin/QuantumWing/blob/master/docs/transactions/signing.md">https://github.com/dolfrin/QuantumWing/blob/master/docs/transactions/signing.md</a></td></tr><tr><td><strong>⛽ Gas &#x26; Fees</strong></td><td>Gas economics and pricing</td><td><a href="https://github.com/dolfrin/QuantumWing/blob/master/docs/transactions/gas-fees.md">https://github.com/dolfrin/QuantumWing/blob/master/docs/transactions/gas-fees.md</a></td></tr><tr><td><strong>📦 Transaction Pool</strong></td><td>Mempool management</td><td><a href="https://github.com/dolfrin/QuantumWing/blob/master/docs/transactions/mempool.md">https://github.com/dolfrin/QuantumWing/blob/master/docs/transactions/mempool.md</a></td></tr></tbody></table>
