forked from MettaChain/PropChain-contract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
579 lines (494 loc) · 18.6 KB
/
Copy pathlib.rs
File metadata and controls
579 lines (494 loc) · 18.6 KB
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
#![allow(clippy::clone_on_copy)] // fires inside ink! generated storage code
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(unexpected_cfgs)]
#![allow(clippy::new_without_default)]
//! # PropChain Database Integration Contract
//!
//! On-chain coordination layer for off-chain database integration providing:
//! - Database synchronization event emission for off-chain indexers
//! - Data export capabilities via structured events
//! - Analytics data aggregation and snapshots
//! - Sync state tracking and verification
//! - Data integrity checksums for off-chain validation
//!
//! ## Architecture
//!
//! This contract acts as the on-chain coordination point:
//! 1. **Sync Events**: Emits structured events that off-chain indexers consume
//! to keep databases synchronized with on-chain state.
//! 2. **Data Export**: Provides batch query endpoints for initial DB population
//! and periodic reconciliation.
//! 3. **Analytics Snapshots**: Records periodic analytics snapshots on-chain
//! that can be verified against off-chain analytics databases.
//! 4. **Integrity Verification**: Stores Merkle roots / checksums of data sets
//! to allow off-chain databases to prove data integrity.
//!
//! Resolves: https://github.com/MettaChain/PropChain-contract/issues/112
use ink::prelude::string::String;
use ink::prelude::vec::Vec;
use ink::storage::Mapping;
#[ink::contract]
pub mod propchain_database {
use super::*;
// Data types extracted to types.rs (Issue #101)
include!("types.rs");
// Error types extracted to errors.rs (Issue #101)
include!("errors.rs");
// ========================================================================
// EVENTS
// ========================================================================
/// Emitted for every data change that off-chain databases should sync
#[ink(event)]
pub struct DataSyncEvent {
#[ink(topic)]
sync_id: SyncId,
#[ink(topic)]
data_type: DataType,
#[ink(topic)]
block_number: u32,
data_checksum: Hash,
record_count: u64,
timestamp: u64,
}
/// Emitted when a sync is confirmed by an indexer
#[ink(event)]
pub struct SyncConfirmed {
#[ink(topic)]
sync_id: SyncId,
#[ink(topic)]
indexer: AccountId,
block_number: u32,
timestamp: u64,
}
/// Emitted when an analytics snapshot is recorded
#[ink(event)]
pub struct AnalyticsSnapshotRecorded {
#[ink(topic)]
snapshot_id: u64,
#[ink(topic)]
block_number: u32,
total_properties: u64,
total_valuation: u128,
integrity_checksum: Hash,
timestamp: u64,
}
/// Emitted when a data export is requested
#[ink(event)]
pub struct DataExportRequested {
#[ink(topic)]
batch_id: ExportBatchId,
#[ink(topic)]
data_type: DataType,
from_id: u64,
to_id: u64,
requested_by: AccountId,
timestamp: u64,
}
/// Emitted when a data export is completed
#[ink(event)]
pub struct DataExportCompleted {
#[ink(topic)]
batch_id: ExportBatchId,
export_checksum: Hash,
timestamp: u64,
}
/// Emitted when an indexer is registered
#[ink(event)]
pub struct IndexerRegistered {
#[ink(topic)]
indexer: AccountId,
name: String,
timestamp: u64,
}
// ========================================================================
// CONTRACT STORAGE
// ========================================================================
#[ink(storage)]
pub struct DatabaseIntegration {
/// Contract admin
admin: AccountId,
/// Sync records
sync_records: Mapping<SyncId, SyncRecord>,
/// Sync counter
sync_counter: SyncId,
/// Analytics snapshots
analytics_snapshots: Mapping<u64, AnalyticsSnapshot>,
/// Snapshot counter
snapshot_counter: u64,
/// Export requests
export_requests: Mapping<ExportBatchId, ExportRequest>,
/// Export counter
export_counter: ExportBatchId,
/// Registered indexers
indexers: Mapping<AccountId, IndexerInfo>,
/// List of registered indexer accounts
indexer_list: Vec<AccountId>,
/// Last sync block per data type (stored as u8 key)
last_sync_block: Mapping<u8, u32>,
/// Authorized data publishers (contracts that can emit sync events)
authorized_publishers: Mapping<AccountId, bool>,
}
// ========================================================================
// IMPLEMENTATION
// ========================================================================
impl DatabaseIntegration {
#[ink(constructor)]
pub fn new() -> Self {
let caller = Self::env().caller();
Self {
admin: caller,
sync_records: Mapping::default(),
sync_counter: 0,
analytics_snapshots: Mapping::default(),
snapshot_counter: 0,
export_requests: Mapping::default(),
export_counter: 0,
indexers: Mapping::default(),
indexer_list: Vec::new(),
last_sync_block: Mapping::default(),
authorized_publishers: Mapping::default(),
}
}
// ====================================================================
// DATA SYNCHRONIZATION
// ====================================================================
/// Emits a sync event for off-chain database synchronization.
/// Called by authorized contracts when data changes occur.
#[ink(message)]
pub fn emit_sync_event(
&mut self,
data_type: DataType,
data_checksum: Hash,
record_count: u64,
) -> Result<SyncId, Error> {
let caller = self.env().caller();
if caller != self.admin && !self.authorized_publishers.get(caller).unwrap_or(false) {
return Err(Error::Unauthorized);
}
self.sync_counter += 1;
let sync_id = self.sync_counter;
let block_number = self.env().block_number();
let timestamp = self.env().block_timestamp();
let record = SyncRecord {
sync_id,
data_type: data_type.clone(),
block_number,
timestamp,
data_checksum,
record_count,
status: SyncStatus::Initiated,
initiated_by: caller,
};
self.sync_records.insert(sync_id, &record);
// Update last sync block for this data type
let dt_key = self.data_type_to_key(&data_type);
self.last_sync_block.insert(dt_key, &block_number);
self.env().emit_event(DataSyncEvent {
sync_id,
data_type,
block_number,
data_checksum,
record_count,
timestamp,
});
Ok(sync_id)
}
/// Confirms a sync operation (called by registered indexer)
#[ink(message)]
pub fn confirm_sync(&mut self, sync_id: SyncId) -> Result<(), Error> {
let caller = self.env().caller();
// Must be a registered indexer
if !self.indexers.contains(caller) {
return Err(Error::IndexerNotFound);
}
let mut record = self.sync_records.get(sync_id).ok_or(Error::SyncNotFound)?;
record.status = SyncStatus::Confirmed;
self.sync_records.insert(sync_id, &record);
// Update indexer's last synced block
if let Some(mut indexer) = self.indexers.get(caller) {
indexer.last_synced_block = record.block_number;
self.indexers.insert(caller, &indexer);
}
self.env().emit_event(SyncConfirmed {
sync_id,
indexer: caller,
block_number: record.block_number,
timestamp: self.env().block_timestamp(),
});
Ok(())
}
/// Verifies sync data integrity by comparing checksums
#[ink(message)]
pub fn verify_sync(
&mut self,
sync_id: SyncId,
verification_checksum: Hash,
) -> Result<bool, Error> {
let mut record = self.sync_records.get(sync_id).ok_or(Error::SyncNotFound)?;
let is_valid = record.data_checksum == verification_checksum;
if is_valid {
record.status = SyncStatus::Verified;
} else {
record.status = SyncStatus::Failed;
}
self.sync_records.insert(sync_id, &record);
Ok(is_valid)
}
// ====================================================================
// ANALYTICS SNAPSHOTS
// ====================================================================
/// Records an analytics snapshot on-chain for later verification
#[ink(message)]
#[allow(clippy::too_many_arguments)]
pub fn record_analytics_snapshot(
&mut self,
total_properties: u64,
total_transfers: u64,
total_escrows: u64,
total_valuation: u128,
avg_valuation: u128,
active_accounts: u64,
integrity_checksum: Hash,
) -> Result<u64, Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.snapshot_counter += 1;
let snapshot_id = self.snapshot_counter;
let block_number = self.env().block_number();
let timestamp = self.env().block_timestamp();
let snapshot = AnalyticsSnapshot {
snapshot_id,
block_number,
timestamp,
total_properties,
total_transfers,
total_escrows,
total_valuation,
avg_valuation,
active_accounts,
integrity_checksum,
created_by: caller,
};
self.analytics_snapshots.insert(snapshot_id, &snapshot);
self.env().emit_event(AnalyticsSnapshotRecorded {
snapshot_id,
block_number,
total_properties,
total_valuation,
integrity_checksum,
timestamp,
});
Ok(snapshot_id)
}
/// Retrieves an analytics snapshot
#[ink(message)]
pub fn get_analytics_snapshot(&self, snapshot_id: u64) -> Option<AnalyticsSnapshot> {
self.analytics_snapshots.get(snapshot_id)
}
/// Gets the latest snapshot ID
#[ink(message)]
pub fn latest_snapshot_id(&self) -> u64 {
self.snapshot_counter
}
// ====================================================================
// DATA EXPORT
// ====================================================================
/// Requests a data export for a specific range
#[ink(message)]
pub fn request_data_export(
&mut self,
data_type: DataType,
from_id: u64,
to_id: u64,
from_block: u32,
to_block: u32,
) -> Result<ExportBatchId, Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
if from_id > to_id || from_block > to_block {
return Err(Error::InvalidDataRange);
}
self.export_counter += 1;
let batch_id = self.export_counter;
let timestamp = self.env().block_timestamp();
let request = ExportRequest {
batch_id,
data_type: data_type.clone(),
from_id,
to_id,
from_block,
to_block,
requested_by: caller,
requested_at: timestamp,
completed: false,
export_checksum: None,
};
self.export_requests.insert(batch_id, &request);
self.env().emit_event(DataExportRequested {
batch_id,
data_type,
from_id,
to_id,
requested_by: caller,
timestamp,
});
Ok(batch_id)
}
/// Marks a data export as completed with verification checksum
#[ink(message)]
pub fn complete_data_export(
&mut self,
batch_id: ExportBatchId,
export_checksum: Hash,
) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
let mut request = self
.export_requests
.get(batch_id)
.ok_or(Error::ExportNotFound)?;
request.completed = true;
request.export_checksum = Some(export_checksum);
self.export_requests.insert(batch_id, &request);
self.env().emit_event(DataExportCompleted {
batch_id,
export_checksum,
timestamp: self.env().block_timestamp(),
});
Ok(())
}
/// Gets export request details
#[ink(message)]
pub fn get_export_request(&self, batch_id: ExportBatchId) -> Option<ExportRequest> {
self.export_requests.get(batch_id)
}
// ====================================================================
// INDEXER MANAGEMENT
// ====================================================================
/// Registers an off-chain indexer
#[ink(message)]
pub fn register_indexer(&mut self, indexer: AccountId, name: String) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
if self.indexers.contains(indexer) {
return Err(Error::IndexerAlreadyRegistered);
}
let info = IndexerInfo {
account: indexer,
name: name.clone(),
last_synced_block: 0,
is_active: true,
registered_at: self.env().block_timestamp(),
};
self.indexers.insert(indexer, &info);
self.indexer_list.push(indexer);
self.env().emit_event(IndexerRegistered {
indexer,
name,
timestamp: self.env().block_timestamp(),
});
Ok(())
}
/// Deactivates an indexer
#[ink(message)]
pub fn deactivate_indexer(&mut self, indexer: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
let mut info = self.indexers.get(indexer).ok_or(Error::IndexerNotFound)?;
info.is_active = false;
self.indexers.insert(indexer, &info);
Ok(())
}
/// Gets indexer information
#[ink(message)]
pub fn get_indexer(&self, indexer: AccountId) -> Option<IndexerInfo> {
self.indexers.get(indexer)
}
/// Gets all registered indexer accounts
#[ink(message)]
pub fn get_indexer_list(&self) -> Vec<AccountId> {
self.indexer_list.clone()
}
// ====================================================================
// PUBLISHER MANAGEMENT
// ====================================================================
/// Authorizes a contract to publish sync events
#[ink(message)]
pub fn authorize_publisher(&mut self, publisher: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.authorized_publishers.insert(publisher, &true);
Ok(())
}
/// Revokes a publisher's authorization
#[ink(message)]
pub fn revoke_publisher(&mut self, publisher: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.authorized_publishers.remove(publisher);
Ok(())
}
// ====================================================================
// QUERY FUNCTIONS
// ====================================================================
/// Gets a sync record
#[ink(message)]
pub fn get_sync_record(&self, sync_id: SyncId) -> Option<SyncRecord> {
self.sync_records.get(sync_id)
}
/// Gets total sync operations count
#[ink(message)]
pub fn total_syncs(&self) -> SyncId {
self.sync_counter
}
/// Gets the last synced block for a data type
#[ink(message)]
pub fn last_synced_block(&self, data_type: DataType) -> u32 {
let key = self.data_type_to_key(&data_type);
self.last_sync_block.get(key).unwrap_or(0)
}
/// Gets admin
#[ink(message)]
pub fn admin(&self) -> AccountId {
self.admin
}
// ====================================================================
// INTERNAL
// ====================================================================
fn data_type_to_key(&self, dt: &DataType) -> u8 {
match dt {
DataType::Properties => 0,
DataType::Transfers => 1,
DataType::Escrows => 2,
DataType::Compliance => 3,
DataType::Valuations => 4,
DataType::Tokens => 5,
DataType::Analytics => 6,
DataType::FullState => 7,
}
}
}
impl Default for DatabaseIntegration {
fn default() -> Self {
Self::new()
}
}
// ========================================================================
// UNIT TESTS
// ========================================================================
// Unit tests extracted to tests.rs (Issue #101)
}