phos-data-network-precompiles 0.1.1

DATA Network EVM precompiles for Phos
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
//! DATA Network IP Graph precompile.

pub mod dispatch;

use std::collections::{HashMap, HashSet};

use alloy_primitives::{address, b256, keccak256, Address, Keccak256, B256, U256};
use alloy_sol_types::SolValue;
use num_bigint::BigUint;

use crate::{storage::StorageCtx, DataNetworkPrecompileError, Result};

pub const IP_GRAPH_ADDRESS: Address = address!("0000000000000000000000000000000000000101");

const ACL_ADDRESS: Address = address!("1640A22a8A086747cD377b73954545e2Dfcc9Cad");
const ACL_SLOT: B256 = b256!("af99b37fdaacca72ee7240cb1435cc9e498aee6ef4edc19c8cc0cd787f4e6800");
const HUNDRED_PERCENT: u64 = 100_000_000;

#[derive(Debug, Default)]
pub struct IpGraph {
    pub(crate) storage: StorageCtx,
}

impl IpGraph {
    fn is_allowed(&self, caller: Address) -> Result<bool> {
        let key = U256::from_be_bytes(keccak256((caller, ACL_SLOT).abi_encode_packed()).0);
        Ok(self.storage.sload(ACL_ADDRESS, key)? == U256::ONE)
    }

    pub fn add_parent_ip(
        &mut self,
        msg_sender: Address,
        ip_id: Address,
        parent_ip_ids: Vec<Address>,
    ) -> Result<()> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to add parent IP",
            ));
        }

        let data_slot = U256::from_be_bytes(keccak256(ip_id).0);

        for (index, parent_ip_id) in parent_ip_ids.iter().enumerate() {
            self.storage.sstore(
                IP_GRAPH_ADDRESS,
                data_slot + U256::from(index),
                U256::from_be_slice(parent_ip_id.as_slice()),
            )?;
        }

        self.storage.sstore(
            IP_GRAPH_ADDRESS,
            U256::from_be_slice(ip_id.as_slice()),
            U256::from(parent_ip_ids.len()),
        )
    }

    pub fn has_parent_ip(
        &self,
        msg_sender: Address,
        ip_id: Address,
        parent_ip_id: Address,
    ) -> Result<bool> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query hasParentIp",
            ));
        }

        let length_slot = U256::from_be_slice(ip_id.as_slice());
        let current_length = self.storage.sload(IP_GRAPH_ADDRESS, length_slot)?;
        let data_slot = U256::from_be_bytes(keccak256(ip_id).0);

        for index in 0..current_length.to::<u64>() {
            let stored_parent = self
                .storage
                .sload(IP_GRAPH_ADDRESS, data_slot + U256::from(index))?;

            if Address::from_word(B256::from(stored_parent)) == parent_ip_id {
                return Ok(true);
            }
        }

        Ok(false)
    }

    pub fn get_parent_ips(&self, msg_sender: Address, ip_id: Address) -> Result<Vec<Address>> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query getParentIps",
            ));
        }

        let length_slot = U256::from_be_slice(ip_id.as_slice());
        let current_length = self.storage.sload(IP_GRAPH_ADDRESS, length_slot)?;
        let data_slot = U256::from_be_bytes(keccak256(ip_id).0);
        let mut parent_ip_ids = Vec::new();

        for index in 0..current_length.to::<u64>() {
            let stored_parent = self
                .storage
                .sload(IP_GRAPH_ADDRESS, data_slot + U256::from(index))?;

            parent_ip_ids.push(Address::from_word(B256::from(stored_parent)));
        }

        Ok(parent_ip_ids)
    }

    pub fn get_parent_ips_count(&self, msg_sender: Address, ip_id: Address) -> Result<U256> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query parent Ips count",
            ));
        }

        self.storage
            .sload(IP_GRAPH_ADDRESS, U256::from_be_slice(ip_id.as_slice()))
    }

    pub fn get_ancestor_ips(&self, msg_sender: Address, ip_id: Address) -> Result<Vec<Address>> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query getAncestorIps",
            ));
        }

        let mut ancestors: Vec<_> = self.find_ancestors(ip_id)?.into_iter().collect();
        ancestors.sort_unstable();

        Ok(ancestors)
    }

    pub fn get_ancestor_ips_count(&self, msg_sender: Address, ip_id: Address) -> Result<U256> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query getAncestorIpsCount",
            ));
        }

        Ok(U256::from(self.find_ancestors(ip_id)?.len()))
    }

    pub fn has_ancestor_ip(
        &self,
        msg_sender: Address,
        ip_id: Address,
        ancestor_ip_id: Address,
    ) -> Result<bool> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query hasAncestorIp",
            ));
        }

        Ok(self.find_ancestors(ip_id)?.contains(&ancestor_ip_id))
    }

    fn find_ancestors(&self, ip_id: Address) -> Result<HashSet<Address>> {
        let mut ancestors = HashSet::new();
        let mut stack = vec![ip_id];

        while let Some(node) = stack.pop() {
            let current_length = self
                .storage
                .sload(IP_GRAPH_ADDRESS, U256::from_be_slice(node.as_slice()))?;
            let data_slot = U256::from_be_bytes(keccak256(node).0);

            for index in 0..current_length.to::<u64>() {
                let stored_parent = self
                    .storage
                    .sload(IP_GRAPH_ADDRESS, data_slot + U256::from(index))?;
                let parent_ip_id = Address::from_word(B256::from(stored_parent));

                if ancestors.insert(parent_ip_id) {
                    stack.push(parent_ip_id);
                }
            }
        }

        Ok(ancestors)
    }

    pub fn set_royalty(
        &mut self,
        msg_sender: Address,
        ip_id: Address,
        parent_ip_id: Address,
        royalty_policy_kind: U256,
        royalty: U256,
    ) -> Result<()> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to set Royalty",
            ));
        }

        if royalty > U256::from(u32::MAX) {
            return Err(DataNetworkPrecompileError::Revert(
                "royalty value exceeds uint32 range",
            ));
        }

        let policy_bytes = royalty_policy_kind.to_be_bytes_trimmed_vec();
        let mut hasher = Keccak256::new();
        hasher.update(ip_id.as_slice());
        hasher.update(parent_ip_id.as_slice());
        hasher.update(&policy_bytes);
        let slot = U256::from_be_bytes(hasher.finalize().0);
        self.storage.sstore(IP_GRAPH_ADDRESS, slot, royalty)?;

        if royalty_policy_kind == U256::ZERO {
            let mut hasher = Keccak256::new();
            hasher.update(parent_ip_id.as_slice());
            hasher.update(&policy_bytes);
            hasher.update(b"royaltyStack");
            let parent_slot = U256::from_be_bytes(hasher.finalize().0);
            let parent_royalty_stack = self.storage.sload(IP_GRAPH_ADDRESS, parent_slot)?;

            let mut hasher = Keccak256::new();
            hasher.update(ip_id.as_slice());
            hasher.update(&policy_bytes);
            hasher.update(b"royaltyStack");
            let royalty_stack_slot = U256::from_be_bytes(hasher.finalize().0);
            let royalty_stack = self.storage.sload(IP_GRAPH_ADDRESS, royalty_stack_slot)?;
            let royalty_stack = royalty_stack
                .wrapping_add(parent_royalty_stack)
                .wrapping_add(royalty);

            self.storage
                .sstore(IP_GRAPH_ADDRESS, royalty_stack_slot, royalty_stack)?;
        }

        Ok(())
    }

    pub fn get_royalty(
        &self,
        msg_sender: Address,
        ip_id: Address,
        ancestor_ip_id: Address,
        royalty_policy_kind: U256,
    ) -> Result<U256> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query getRoyalty",
            ));
        }

        let total_royalty = match royalty_policy_kind {
            U256::ZERO => self.get_royalty_lap(ip_id, ancestor_ip_id)?,
            U256::ONE => self.get_royalty_lrp(ip_id, ancestor_ip_id)?,
            _ => {
                return Err(DataNetworkPrecompileError::Revert(
                    "unknown royalty policy kind",
                ));
            }
        };

        if total_royalty > BigUint::from(u32::MAX) {
            return Err(DataNetworkPrecompileError::Revert(
                "royalty value exceeds uint32 range",
            ));
        }

        Ok(U256::from_be_slice(&total_royalty.to_bytes_be()))
    }

    fn get_royalty_lap(&self, ip_id: Address, ancestor_ip_id: Address) -> Result<BigUint> {
        let mut royalties = HashMap::new();
        let mut path_counts = HashMap::new();
        royalties.insert(ip_id, BigUint::from(HUNDRED_PERCENT));
        path_counts.insert(ip_id, BigUint::from(1u8));

        let (topo_order, all_parents) = self.topological_sort(ip_id, ancestor_ip_id)?;
        let policy_bytes = U256::ZERO.to_be_bytes_trimmed_vec();

        for node in topo_order.into_iter().rev() {
            if node == ancestor_ip_id {
                break;
            }

            let Some(parents) = all_parents.get(&node) else {
                continue;
            };
            let contribution = path_counts.get(&node).cloned().ok_or_else(|| {
                DataNetworkPrecompileError::Fatal(
                    "missing path count while calculating LAP royalty".into(),
                )
            })?;

            for parent_ip_id in parents {
                let mut hasher = Keccak256::new();
                hasher.update(node.as_slice());
                hasher.update(parent_ip_id.as_slice());
                hasher.update(&policy_bytes);
                let royalty_slot = U256::from_be_bytes(hasher.finalize().0);
                let parent_royalty = self.storage.sload(IP_GRAPH_ADDRESS, royalty_slot)?;
                let parent_royalty = BigUint::from_bytes_be(&parent_royalty.to_be_bytes::<32>());

                *path_counts.entry(*parent_ip_id).or_default() += &contribution;
                *royalties.entry(*parent_ip_id).or_default() += &contribution * parent_royalty;
            }
        }

        Ok(royalties.remove(&ancestor_ip_id).unwrap_or_default())
    }

    fn get_royalty_lrp(&self, ip_id: Address, ancestor_ip_id: Address) -> Result<BigUint> {
        let mut royalties = HashMap::new();
        royalties.insert(ip_id, BigUint::from(HUNDRED_PERCENT));

        let (topo_order, all_parents) = self.topological_sort(ip_id, ancestor_ip_id)?;
        let policy_bytes = U256::ONE.to_be_bytes_trimmed_vec();

        for node in topo_order.into_iter().rev() {
            if node == ancestor_ip_id {
                break;
            }

            let current_royalty = royalties.get(&node).cloned().unwrap_or_default();
            if current_royalty == BigUint::default() {
                continue;
            }

            let Some(parents) = all_parents.get(&node) else {
                continue;
            };

            for parent_ip_id in parents {
                let mut hasher = Keccak256::new();
                hasher.update(node.as_slice());
                hasher.update(parent_ip_id.as_slice());
                hasher.update(&policy_bytes);
                let royalty_slot = U256::from_be_bytes(hasher.finalize().0);
                let parent_royalty = self.storage.sload(IP_GRAPH_ADDRESS, royalty_slot)?;
                let parent_royalty = BigUint::from_bytes_be(&parent_royalty.to_be_bytes::<32>());
                let contribution =
                    &current_royalty * parent_royalty / BigUint::from(HUNDRED_PERCENT);

                *royalties.entry(*parent_ip_id).or_default() += contribution;
            }
        }

        Ok(royalties.remove(&ancestor_ip_id).unwrap_or_default())
    }

    #[allow(clippy::type_complexity)]
    fn topological_sort(
        &self,
        ip_id: Address,
        ancestor_ip_id: Address,
    ) -> Result<(Vec<Address>, HashMap<Address, Vec<Address>>)> {
        let mut all_parents = HashMap::<Address, Vec<Address>>::new();
        let mut visited = HashSet::new();
        let mut in_topo_order = HashSet::new();
        let mut topo_order = Vec::new();
        let mut stack = vec![ip_id];

        while let Some(current) = stack.pop() {
            if visited.contains(&current) {
                if in_topo_order.insert(current) {
                    topo_order.push(current);
                }
                continue;
            }

            visited.insert(current);
            stack.push(current);

            let current_length = self
                .storage
                .sload(IP_GRAPH_ADDRESS, U256::from_be_slice(current.as_slice()))?;
            let data_slot = U256::from_be_bytes(keccak256(current).0);

            for index in 0..current_length.to::<u64>() {
                let stored_parent = self
                    .storage
                    .sload(IP_GRAPH_ADDRESS, data_slot + U256::from(index))?;
                let parent_ip_id = Address::from_word(B256::from(stored_parent));
                all_parents.entry(current).or_default().push(parent_ip_id);

                if !visited.contains(&parent_ip_id) {
                    stack.push(parent_ip_id);
                }
            }
        }

        if !visited.contains(&ancestor_ip_id) {
            return Ok((Vec::new(), HashMap::new()));
        }

        Ok((topo_order, all_parents))
    }

    pub fn get_royalty_stack(
        &self,
        msg_sender: Address,
        ip_id: Address,
        royalty_policy_kind: U256,
    ) -> Result<U256> {
        if !self.is_allowed(msg_sender)? {
            return Err(DataNetworkPrecompileError::Unauthorized(
                "caller not allowed to query getRoyaltyStack",
            ));
        }

        match royalty_policy_kind {
            U256::ZERO => self.get_royalty_stack_lap(ip_id),
            U256::ONE => self.get_royalty_stack_lrp(ip_id),
            _ => Err(DataNetworkPrecompileError::Revert(
                "unknown royalty policy kind",
            )),
        }
    }

    fn get_royalty_stack_lap(&self, ip_id: Address) -> Result<U256> {
        let policy_bytes = U256::ZERO.to_be_bytes_trimmed_vec();
        let mut hasher = Keccak256::new();
        hasher.update(ip_id.as_slice());
        hasher.update(&policy_bytes);
        hasher.update(b"royaltyStack");
        let slot = U256::from_be_bytes(hasher.finalize().0);

        self.storage.sload(IP_GRAPH_ADDRESS, slot)
    }

    fn get_royalty_stack_lrp(&self, ip_id: Address) -> Result<U256> {
        let current_length = self
            .storage
            .sload(IP_GRAPH_ADDRESS, U256::from_be_slice(ip_id.as_slice()))?;
        let data_slot = U256::from_be_bytes(keccak256(ip_id).0);
        let policy_bytes = U256::ONE.to_be_bytes_trimmed_vec();
        let mut total_royalty = U256::ZERO;

        for index in 0..current_length.to::<u64>() {
            let stored_parent = self
                .storage
                .sload(IP_GRAPH_ADDRESS, data_slot + U256::from(index))?;
            let parent_ip_id = Address::from_word(B256::from(stored_parent));

            let mut hasher = Keccak256::new();
            hasher.update(ip_id.as_slice());
            hasher.update(parent_ip_id.as_slice());
            hasher.update(&policy_bytes);
            let royalty_slot = U256::from_be_bytes(hasher.finalize().0);
            let royalty = self.storage.sload(IP_GRAPH_ADDRESS, royalty_slot)?;

            total_royalty = total_royalty.wrapping_add(royalty);
        }

        Ok(total_royalty)
    }
}