constellation-metagraph-sdk 0.2.0

Rust SDK for signing data and currency transactions on Constellation Network metagraphs built with metakit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# Constellation Metagraph SDK - Rust

Rust SDK for signing data and currency transactions on Constellation Network metagraphs built with the [metakit](https://github.com/Constellation-Labs/metakit) framework.

> **Scope:** This SDK supports both data transactions (state updates) and metagraph token transactions (value transfers). It implements the standardized serialization, hashing, and signing routines defined by metakit and may not be compatible with metagraphs using custom serialization.

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
constellation-metagraph-sdk = "0.2"
```

Or use cargo:

```bash
cargo add constellation-metagraph-sdk
```

## Quick Start

### Data Transactions

```rust
use constellation_sdk::{
    wallet::generate_key_pair,
    signed_object::create_signed_object,
    verify::verify,
};
use serde_json::json;

fn main() {
    // Generate a key pair
    let key_pair = generate_key_pair();
    println!("Address: {}", key_pair.address);

    // Sign data
    let data = json!({ "action": "UPDATE", "payload": { "key": "value" } });
    let signed = create_signed_object(&data, &key_pair.private_key, false).unwrap();

    // Verify
    let result = verify(&signed, false);
    println!("Valid: {}", result.is_valid);
}
```

### Currency Transactions

```rust
use constellation_sdk::{
    generate_key_pair,
    create_currency_transaction,
    verify_currency_transaction,
    TransferParams,
    TransactionReference,
};

fn main() {
    // Generate keys
    let sender = generate_key_pair();
    let recipient = generate_key_pair();

    // Create token transaction
    let tx = create_currency_transaction(
        TransferParams {
            destination: recipient.address,
            amount: 100.5,
            fee: 0.0,
        },
        &sender.private_key,
        TransactionReference {
            hash: "abc123...".to_string(),
            ordinal: 0,
        },
    ).unwrap();

    // Verify
    let result = verify_currency_transaction(&tx);
    println!("Valid: {}", result.is_valid);
}
```

## API Reference

### Data Transactions

#### High-Level API

#### `create_signed_object(value, private_key, is_data_update) -> Result<Signed<T>>`

Create a signed object with a single signature.

```rust
let signed = create_signed_object(&data, &private_key, false)?;

// For L1 submission (DataUpdate)
let signed = create_signed_object(&data, &private_key, true)?;
```

#### `add_signature(signed, private_key, is_data_update) -> Result<Signed<T>>`

Add an additional signature to an existing signed object.

```rust
let mut signed = create_signed_object(&data, &party1_key, false)?;
signed = add_signature(&signed, &party2_key, false)?;
// signed.proofs.len() == 2
```

#### `batch_sign(value, private_keys, is_data_update) -> Result<Signed<T>>`

Create a signed object with multiple signatures at once.

```rust
let signed = batch_sign(&data, &[key1, key2, key3], false)?;
// signed.proofs.len() == 3
```

#### `verify(signed, is_data_update) -> VerificationResult`

Verify all signatures on a signed object.

```rust
let result = verify(&signed, false);
if result.is_valid {
    println!("All signatures valid");
} else {
    println!("Invalid proofs: {:?}", result.invalid_proofs);
}
```

### Low-Level Primitives

#### `canonicalize(data) -> Result<String>`

Canonicalize JSON data according to RFC 8785.

```rust
let canonical = canonicalize(&json!({"b": 2, "a": 1}))?;
// "{\"a\":1,\"b\":2}"
```

#### `to_bytes(data, is_data_update) -> Result<Vec<u8>>`

Convert data to binary bytes for signing.

```rust
// Regular encoding
let bytes = to_bytes(&data, false)?;

// DataUpdate encoding (with Constellation prefix)
let bytes = to_bytes(&data, true)?;
```

#### `hash_data(data) -> Result<Hash>` / `hash_bytes(bytes) -> Hash`

Compute SHA-256 hash.

```rust
let hash = hash_data(&data)?;
println!("{}", hash.value);  // 64-char hex
println!("{:?}", hash.bytes); // [u8; 32]
```

#### `sign(data, private_key)` / `sign_data_update(data, private_key)`

Sign data and return a proof.

```rust
let proof = sign(&data, &private_key)?;
// SignatureProof { id: "...", signature: "..." }
```

#### `sign_hash(hash_hex, private_key) -> Result<String>`

Sign a pre-computed hash.

```rust
let hash = hash_data(&data)?;
let signature = sign_hash(&hash.value, &private_key)?;
```

### Wallet Utilities

#### `generate_key_pair() -> KeyPair`

Generate a new random key pair.

```rust
let key_pair = generate_key_pair();
// KeyPair { private_key, public_key, address }
```

#### `key_pair_from_private_key(private_key) -> Result<KeyPair>`

Derive a key pair from an existing private key.

```rust
let key_pair = key_pair_from_private_key(&existing_private_key)?;
```

#### `get_public_key_id(private_key) -> Result<String>`

Get the public key ID (128 chars, no 04 prefix) for use in proofs.

```rust
let id = get_public_key_id(&private_key)?;
```

### Currency Transactions

#### `create_currency_transaction(params, private_key, last_ref) -> Result<CurrencyTransaction>`

Create a metagraph token transaction.

```rust
use constellation_sdk::{create_currency_transaction, TransferParams, TransactionReference};

let tx = create_currency_transaction(
    TransferParams {
        destination: "DAG...recipient".to_string(),
        amount: 100.5,  // 100.5 tokens
        fee: 0.0,
    },
    &private_key,
    TransactionReference {
        hash: "abc123...".to_string(),
        ordinal: 5,
    },
)?;
```

#### `create_currency_transaction_batch(transfers, private_key, last_ref) -> Result<Vec<CurrencyTransaction>>`

Create multiple token transactions in a batch.

```rust
let transfers = vec![
    TransferParams { destination: "DAG...1".to_string(), amount: 10.0, fee: 0.0 },
    TransferParams { destination: "DAG...2".to_string(), amount: 20.0, fee: 0.0 },
    TransferParams { destination: "DAG...3".to_string(), amount: 30.0, fee: 0.0 },
];

let txns = create_currency_transaction_batch(
    transfers,
    &private_key,
    TransactionReference { hash: "abc123...".to_string(), ordinal: 5 },
)?;
```

#### `sign_currency_transaction(transaction, private_key) -> Result<CurrencyTransaction>`

Add an additional signature to a currency transaction (for multi-sig).

```rust
let mut tx = create_currency_transaction(params, &key1, last_ref)?;
tx = sign_currency_transaction(&tx, &key2)?;
// tx.proofs.len() == 2
```

#### `verify_currency_transaction(transaction) -> VerificationResult`

Verify all signatures on a currency transaction.

```rust
let result = verify_currency_transaction(&tx);
println!("Valid: {}", result.is_valid);
```

#### `hash_currency_transaction(transaction) -> Hash`

Hash a currency transaction.

```rust
let hash = hash_currency_transaction(&tx);
println!("Hash: {}", hash.value);
```

#### `get_transaction_reference(transaction, ordinal) -> TransactionReference`

Get a transaction reference for chaining transactions.

```rust
let tx_ref = get_transaction_reference(&tx, 6);
// Use tx_ref as last_ref for next transaction
```

#### Utility Functions

```rust
// Validate DAG address
is_valid_dag_address("DAG...");  // true/false

// Convert between token units and smallest units
token_to_units(100.5);    // 10050000000
units_to_token(10050000000);  // 100.5

// Token decimals constant
TOKEN_DECIMALS;  // 1e-8
```

### Network Operations

Enable the `network` feature in your `Cargo.toml`:

```toml
[dependencies]
constellation-metagraph-sdk = { version = "0.2", features = ["network"] }
```

#### `CurrencyL1Client`

Client for interacting with Currency L1 nodes.

```rust
use constellation_sdk::network::{CurrencyL1Client, NetworkConfig};

let config = NetworkConfig {
    l1_url: Some("http://localhost:9010".to_string()),
    timeout: Some(30),  // optional, defaults to 30s
    ..Default::default()
};

let client = CurrencyL1Client::new(config)?;

// Get last transaction reference for an address
let last_ref = client.get_last_reference("DAG...").await?;

// Submit a signed transaction
let result = client.post_transaction(&signed_tx).await?;
println!("Transaction hash: {}", result.hash);

// Check pending transaction status
if let Some(pending) = client.get_pending_transaction(&result.hash).await? {
    println!("Status: {:?}", pending.status);  // Waiting, InProgress, or Accepted
}

// Check node health
let is_healthy = client.check_health().await;
```

#### `DataL1Client`

Client for interacting with Data L1 nodes (metagraphs).

```rust
use constellation_sdk::network::{DataL1Client, NetworkConfig};

let config = NetworkConfig {
    data_l1_url: Some("http://localhost:8080".to_string()),
    ..Default::default()
};

let client = DataL1Client::new(config)?;

// Estimate fee for data submission
let fee_info = client.estimate_fee(&signed_data).await?;
println!("Fee: {}, Address: {}", fee_info.fee, fee_info.address);

// Submit signed data
let result = client.post_data(&signed_data).await?;
println!("Data hash: {}", result.hash);

// Check node health
let is_healthy = client.check_health().await;
```

#### Combined Configuration

```rust
let config = NetworkConfig {
    l1_url: Some("http://localhost:9010".to_string()),      // Currency L1
    data_l1_url: Some("http://localhost:8080".to_string()), // Data L1
    timeout: Some(30),
};

let l1_client = CurrencyL1Client::new(config.clone())?;
let data_client = DataL1Client::new(config)?;
```

#### Network Types

```rust
pub struct NetworkConfig {
    pub l1_url: Option<String>,       // Currency L1 endpoint
    pub data_l1_url: Option<String>,  // Data L1 endpoint
    pub timeout: Option<u64>,         // Request timeout in seconds
}

pub struct PostTransactionResponse {
    pub hash: String,
}

pub struct PendingTransaction {
    pub hash: String,
    pub status: TransactionStatus,  // Waiting, InProgress, Accepted
    pub transaction: CurrencyTransaction,
}

pub struct EstimateFeeResponse {
    pub fee: i64,
    pub address: String,
}

pub struct PostDataResponse {
    pub hash: String,
}

pub enum NetworkError {
    HttpError { message: String, status_code: Option<u16>, response: Option<String> },
    Timeout,
    ConfigError(String),
    SerializationError(String),
}
```

## Types

```rust
pub struct SignatureProof {
    pub id: String,        // Public key (128 chars)
    pub signature: String, // DER signature hex
}

pub struct Signed<T> {
    pub value: T,
    pub proofs: Vec<SignatureProof>,
}

pub struct KeyPair {
    pub private_key: String,
    pub public_key: String,
    pub address: String,
}

pub struct Hash {
    pub value: String,     // 64-char hex
    pub bytes: [u8; 32],   // 32 bytes
}

pub struct VerificationResult {
    pub is_valid: bool,
    pub valid_proofs: Vec<SignatureProof>,
    pub invalid_proofs: Vec<SignatureProof>,
}

// Currency transaction types
pub struct TransactionReference {
    pub hash: String,      // 64-char hex transaction hash
    pub ordinal: i64,      // Transaction ordinal number
}

pub struct CurrencyTransactionValue {
    pub source: String,         // Source DAG address
    pub destination: String,    // Destination DAG address
    pub amount: i64,           // Amount in smallest units (1e-8)
    pub fee: i64,              // Fee in smallest units (1e-8)
    pub parent: TransactionReference,
    pub salt: String,          // Random salt for uniqueness
}

pub type CurrencyTransaction = Signed<CurrencyTransactionValue>;

pub struct TransferParams {
    pub destination: String,   // Destination DAG address
    pub amount: f64,          // Amount in token units (e.g., 100.5 tokens)
    pub fee: f64,             // Fee in token units (defaults to 0)
}
```

## Usage Examples

### Submit DataUpdate to L1

```rust
use constellation_sdk::{
    wallet::generate_key_pair,
    signed_object::create_signed_object,
};
use serde_json::json;

let data_update = json!({
    "action": "TRANSFER",
    "from": "address1",
    "to": "address2",
    "amount": 100
});

// Sign as DataUpdate
let signed = create_signed_object(&data_update, &private_key, true)?;

// Submit to data-l1 (using your HTTP client)
// POST http://l1-node:9300/data with signed as JSON body
```

### Multi-Signature Workflow

```rust
use constellation_sdk::{
    signed_object::{create_signed_object, add_signature},
    verify::verify,
};

// Party 1 creates and signs
let mut signed = create_signed_object(&data, &party1_key, false)?;

// Party 2 adds signature
signed = add_signature(&signed, &party2_key, false)?;

// Party 3 adds signature
signed = add_signature(&signed, &party3_key, false)?;

// Verify all signatures
let result = verify(&signed, false);
println!("{} valid signatures", result.valid_proofs.len());
```

### Currency Transactions

#### Create and Verify Token Transaction

```rust
use constellation_sdk::{
    generate_key_pair,
    create_currency_transaction,
    verify_currency_transaction,
    TransferParams,
    TransactionReference,
};

// Generate keys
let sender_key = generate_key_pair();
let recipient_key = generate_key_pair();

// Get last transaction reference (from network or previous transaction)
let last_ref = TransactionReference {
    hash: "abc123...previous-tx-hash".to_string(),
    ordinal: 5,
};

// Create transaction
let tx = create_currency_transaction(
    TransferParams {
        destination: recipient_key.address.clone(),
        amount: 100.5,  // 100.5 tokens
        fee: 0.0,
    },
    &sender_key.private_key,
    last_ref,
)?;

// Verify
let result = verify_currency_transaction(&tx);
println!("Transaction valid: {}", result.is_valid);

// Note: Network submission not yet implemented in this SDK
// You can submit the transaction using dag4.js or custom network code
```

#### Batch Token Transactions

```rust
use constellation_sdk::{
    create_currency_transaction_batch,
    TransferParams,
    TransactionReference,
};

let last_ref = TransactionReference {
    hash: "abc123...".to_string(),
    ordinal: 10,
};

let transfers = vec![
    TransferParams { destination: "DAG...1".to_string(), amount: 10.0, fee: 0.0 },
    TransferParams { destination: "DAG...2".to_string(), amount: 20.0, fee: 0.0 },
    TransferParams { destination: "DAG...3".to_string(), amount: 30.0, fee: 0.0 },
];

// Create batch (transactions are automatically chained)
let txns = create_currency_transaction_batch(
    transfers,
    &private_key,
    last_ref,
)?;

// txns[0].value.parent.ordinal == 10
// txns[1].value.parent.ordinal == 11
// txns[2].value.parent.ordinal == 12
```

#### Multi-Signature Token Transaction

```rust
use constellation_sdk::{
    create_currency_transaction,
    sign_currency_transaction,
    verify_currency_transaction,
    TransferParams,
    TransactionReference,
};

let key1 = generate_key_pair();
let key2 = generate_key_pair();
let recipient = generate_key_pair();

let last_ref = TransactionReference {
    hash: "abc123...".to_string(),
    ordinal: 0,
};

// Create transaction with first signature
let mut tx = create_currency_transaction(
    TransferParams {
        destination: recipient.address.clone(),
        amount: 100.0,
        fee: 0.0,
    },
    &key1.private_key,
    last_ref,
)?;

// Add second signature
tx = sign_currency_transaction(&tx, &key2.private_key)?;

// Verify both signatures
let result = verify_currency_transaction(&tx);
println!("{} valid signatures", result.valid_proofs.len());
```

## Development

```bash
# Run tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Check for issues
cargo clippy

# Format code
cargo fmt

# Build release
cargo build --release
```

## License

Apache-2.0