Created
November 12, 2023 07:43
-
-
Save MASDXI/e0e7b606a2e92575b9cd90e6ec80daed to your computer and use it in GitHub Desktop.
TrieDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity 0.8.14; | |
contract TrieDB { | |
enum TRIE_STATUS { INACTIVE, ACTIVE } | |
struct TrieNode { | |
bytes32 origin; | |
TRIE_STATUS status; | |
Transaction [] txChange; | |
} | |
struct Transaction { | |
uint256 amount; | |
bytes32 extraData; | |
} | |
mapping(bytes32 => TrieNode) public _trie; | |
mapping(address => uint256) public _trieCount; | |
function _hash(address account, uint256 Id) public pure returns (bytes32) { | |
return bytes32(abi.encode(keccak256(abi.encode(account, Id)))); | |
} | |
function _create(address account, uint256 amount, bytes32 origin, bytes32 data) public returns (bool) { | |
bytes32 TrieHash = _hash(account, _trieCount[account]); | |
if (_trie[TrieHash].status == TRIE_STATUS.INACTIVE) { | |
_trie[TrieHash].origin = origin; | |
_trie[TrieHash].txChange.push(Transaction(amount,data)); | |
_trieCount[account]++; | |
} | |
return true; | |
} | |
function _spend(address account, uint256 amount, uint256 id) public returns (bool) { | |
bytes32 TrieHashOrigin = _hash(msg.sender, id); | |
bytes32 TrieHash = _hash(msg.sender, id); | |
TrieNode storage trie = _trie[TrieHash]; | |
Transaction storage transac = trie.txChange[trie.txChange.length-1]; | |
_create(account, amount, _trie[TrieHashOrigin].origin, ""); | |
trie.txChange.push(Transaction(transac.amount - amount, transac.extraData)); | |
return true; | |
} | |
function getTrie(bytes32 TireId) public view returns (TrieNode memory, Transaction memory) { | |
TrieNode memory trieCache = _trie[TireId]; | |
return (trieCache, trieCache.txChange[trieCache.txChange.length-1]); | |
} | |
function getTx(bytes32 TireId) public view returns (Transaction [] memory) { | |
TrieNode memory trieCache = _trie[TireId]; | |
return trieCache.txChange; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment