Skip to content
Snippets Groups Projects
Commit 7c5ab533 authored by Éloïs's avatar Éloïs
Browse files

[ref] gva: move gva db definition in new crate duniter-gva-db

parent 781131b0
Branches
No related tags found
No related merge requests found
Showing
with 345 additions and 197 deletions
...@@ -1092,6 +1092,7 @@ dependencies = [ ...@@ -1092,6 +1092,7 @@ dependencies = [
"dubp", "dubp",
"duniter-dbs", "duniter-dbs",
"duniter-dbs-write-ops", "duniter-dbs-write-ops",
"duniter-gva-db",
"duniter-gva-indexer", "duniter-gva-indexer",
"fast-threadpool", "fast-threadpool",
"flume", "flume",
...@@ -1156,6 +1157,7 @@ dependencies = [ ...@@ -1156,6 +1157,7 @@ dependencies = [
"dubp", "dubp",
"duniter-conf", "duniter-conf",
"duniter-dbs", "duniter-dbs",
"duniter-gva-db",
"duniter-gva-dbs-reader", "duniter-gva-dbs-reader",
"duniter-gva-gql", "duniter-gva-gql",
"duniter-gva-indexer", "duniter-gva-indexer",
...@@ -1176,6 +1178,22 @@ dependencies = [ ...@@ -1176,6 +1178,22 @@ dependencies = [
"warp", "warp",
] ]
[[package]]
name = "duniter-gva-db"
version = "0.1.0"
dependencies = [
"bincode",
"chrono",
"dubp",
"duniter-dbs",
"kv_typed",
"paste",
"serde",
"serde_json",
"uninit",
"zerocopy",
]
[[package]] [[package]]
name = "duniter-gva-dbs-reader" name = "duniter-gva-dbs-reader"
version = "0.1.0" version = "0.1.0"
...@@ -1183,6 +1201,7 @@ dependencies = [ ...@@ -1183,6 +1201,7 @@ dependencies = [
"anyhow", "anyhow",
"dubp", "dubp",
"duniter-dbs", "duniter-dbs",
"duniter-gva-db",
"maplit", "maplit",
"resiter", "resiter",
"smallvec", "smallvec",
...@@ -1201,6 +1220,7 @@ dependencies = [ ...@@ -1201,6 +1220,7 @@ dependencies = [
"duniter-bc-reader", "duniter-bc-reader",
"duniter-conf", "duniter-conf",
"duniter-dbs", "duniter-dbs",
"duniter-gva-db",
"duniter-gva-dbs-reader", "duniter-gva-dbs-reader",
"duniter-mempools", "duniter-mempools",
"duniter-module", "duniter-module",
...@@ -1223,6 +1243,7 @@ dependencies = [ ...@@ -1223,6 +1243,7 @@ dependencies = [
"anyhow", "anyhow",
"dubp", "dubp",
"duniter-dbs", "duniter-dbs",
"duniter-gva-db",
"maplit", "maplit",
"once_cell", "once_cell",
"resiter", "resiter",
......
...@@ -25,6 +25,7 @@ dirs = "3.0.1" ...@@ -25,6 +25,7 @@ dirs = "3.0.1"
dubp = { version = "0.34.0" } dubp = { version = "0.34.0" }
duniter-dbs = { path = "../../rust-libs/duniter-dbs", default-features = false, features = ["explorer", "leveldb_backend", "sled_backend"] } duniter-dbs = { path = "../../rust-libs/duniter-dbs", default-features = false, features = ["explorer", "leveldb_backend", "sled_backend"] }
duniter-dbs-write-ops = { path = "../../rust-libs/duniter-dbs-write-ops", default-features = false, features = ["explorer", "leveldb_backend", "sled_backend"] } duniter-dbs-write-ops = { path = "../../rust-libs/duniter-dbs-write-ops", default-features = false, features = ["explorer", "leveldb_backend", "sled_backend"] }
duniter-gva-db = { path = "../../rust-libs/modules/gva/db", default-features = false, features = ["explorer", "leveldb_backend"] }
duniter-gva-indexer = { path = "../../rust-libs/modules/gva/indexer" } duniter-gva-indexer = { path = "../../rust-libs/modules/gva/indexer" }
fast-threadpool = "0.2.3" fast-threadpool = "0.2.3"
flume = "0.10.0" flume = "0.10.0"
......
...@@ -36,7 +36,6 @@ use duniter_dbs::databases::{ ...@@ -36,7 +36,6 @@ use duniter_dbs::databases::{
bc_v1::{BcV1Db, BcV1DbWritable}, bc_v1::{BcV1Db, BcV1DbWritable},
bc_v2::{BcV2Db, BcV2DbWritable}, bc_v2::{BcV2Db, BcV2DbWritable},
dunp_v1::{DunpV1Db, DunpV1DbWritable}, dunp_v1::{DunpV1Db, DunpV1DbWritable},
gva_v1::{GvaV1Db, GvaV1DbWritable},
txs_mp_v2::{TxsMpV2Db, TxsMpV2DbWritable}, txs_mp_v2::{TxsMpV2Db, TxsMpV2DbWritable},
}; };
use duniter_dbs::kv_typed::prelude::*; use duniter_dbs::kv_typed::prelude::*;
...@@ -44,6 +43,7 @@ use duniter_dbs::prelude::*; ...@@ -44,6 +43,7 @@ use duniter_dbs::prelude::*;
use duniter_dbs::regex::Regex; use duniter_dbs::regex::Regex;
use duniter_dbs::serde_json::{Map, Value}; use duniter_dbs::serde_json::{Map, Value};
use duniter_dbs::smallvec::{smallvec, SmallVec}; use duniter_dbs::smallvec::{smallvec, SmallVec};
use duniter_gva_db::{GvaV1Db, GvaV1DbWritable};
use rayon::prelude::*; use rayon::prelude::*;
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
......
...@@ -37,7 +37,7 @@ unwrap = "1.2.1" ...@@ -37,7 +37,7 @@ unwrap = "1.2.1"
[features] [features]
default = ["sled_backend"] default = ["sled_backend"]
# CAUTION: feature "leveldb_backend" MUST BE DISABLED by default. Uncomment this lire for dev/test only ! # CAUTION: feature "leveldb_backend" MUST BE DISABLED by default. Uncomment this line for dev/test only !
#default = ["sled_backend", "explorer", "leveldb_backend"] #default = ["sled_backend", "explorer", "leveldb_backend"]
explorer = ["chrono", "kv_typed/explorer"] explorer = ["chrono", "kv_typed/explorer"]
......
...@@ -17,5 +17,4 @@ pub mod bc_v1; ...@@ -17,5 +17,4 @@ pub mod bc_v1;
pub mod bc_v2; pub mod bc_v2;
pub mod cm_v1; pub mod cm_v1;
pub mod dunp_v1; pub mod dunp_v1;
pub mod gva_v1;
pub mod txs_mp_v2; pub mod txs_mp_v2;
...@@ -26,4 +26,3 @@ pub mod ud_id; ...@@ -26,4 +26,3 @@ pub mod ud_id;
pub mod uid; pub mod uid;
pub mod utxo_id; pub mod utxo_id;
pub mod wallet_conditions; pub mod wallet_conditions;
pub mod wallet_hash_with_bn;
...@@ -98,137 +98,6 @@ impl ExplorableKey for UtxoIdDbV2 { ...@@ -98,137 +98,6 @@ impl ExplorableKey for UtxoIdDbV2 {
} }
} }
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct GvaUtxoIdDbV1([u8; 69]); // script hash ++ block_number ++ tx_hash ++ output_index
impl Default for GvaUtxoIdDbV1 {
fn default() -> Self {
GvaUtxoIdDbV1([0u8; 69])
}
}
impl std::fmt::Display for GvaUtxoIdDbV1 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}:{}:{}:{}",
self.get_script_hash(),
self.get_block_number(),
self.get_tx_hash(),
self.get_output_index()
)
}
}
impl GvaUtxoIdDbV1 {
pub fn get_script_hash(&self) -> Hash {
let mut buffer = uninit_array![u8; 32];
buffer.as_out().copy_from_slice(&self.0[..32]);
Hash(unsafe { std::mem::transmute(buffer) })
}
pub fn get_block_number(&self) -> u32 {
let mut buffer = uninit_array![u8; 4];
buffer.as_out().copy_from_slice(&self.0[32..36]);
u32::from_be_bytes(unsafe { std::mem::transmute(buffer) })
}
pub fn get_tx_hash(&self) -> Hash {
let mut buffer = uninit_array![u8; 32];
buffer.as_out().copy_from_slice(&self.0[36..68]);
Hash(unsafe { std::mem::transmute(buffer) })
}
pub fn get_output_index(&self) -> u8 {
self.0[68]
}
pub fn new(
script: WalletScriptV10,
block_number: u32,
tx_hash: Hash,
output_index: u8,
) -> Self {
let script_hash = Hash::compute(script.to_string().as_bytes());
Self::new_(script_hash, block_number, tx_hash, output_index)
}
pub fn new_(script_hash: Hash, block_number: u32, tx_hash: Hash, output_index: u8) -> Self {
// TODO uncomment when feature const_generics became stable !
/*let mut buffer = uninit_array![u8; 69];
let (hash_buffer, rest_buffer) = buffer.as_out().split_at_out(32);
let (bn_buffer, rest_buffer) = rest_buffer.split_at_out(4);
let (tx_hash_buffer, output_index_buffer) = rest_buffer.split_at_out(32);
hash_buffer.copy_from_slice(script_hash.as_ref());
bn_buffer.copy_from_slice(&block_number.to_be_bytes()[..]);
tx_hash_buffer.copy_from_slice(tx_hash.as_ref());
output_index_buffer.copy_from_slice(&[output_index]);
Self(unsafe { std::mem::transmute(buffer) })*/
let mut buffer = [0u8; 69];
buffer[..32].copy_from_slice(script_hash.as_ref());
buffer[32..36].copy_from_slice(&block_number.to_be_bytes()[..]);
buffer[36..68].copy_from_slice(tx_hash.as_ref());
buffer[68] = output_index;
Self(buffer)
}
pub fn script_interval(script_hash: Hash) -> (Self, Self) {
let mut buffer = [0; 69];
buffer[..32].copy_from_slice(script_hash.as_ref());
let min = Self(buffer);
let mut buffer = [255; 69];
buffer[..32].copy_from_slice(script_hash.as_ref());
let max = Self(buffer);
(min, max)
}
pub fn script_block_interval(
script_hash: Hash,
block_number_start: u32,
block_number_end: u32,
) -> (Self, Self) {
(
Self::new_(script_hash, block_number_start, Hash::default(), 0),
Self::new_(script_hash, block_number_end, Hash::max(), u8::MAX),
)
}
}
impl AsBytes for GvaUtxoIdDbV1 {
fn as_bytes<T, F: FnMut(&[u8]) -> T>(&self, mut f: F) -> T {
f(&self.0[..])
}
}
impl FromBytes for GvaUtxoIdDbV1 {
type Err = CorruptedBytes;
fn from_bytes(bytes: &[u8]) -> std::result::Result<Self, Self::Err> {
if bytes.len() == 69 {
// TODO uncomment when feature const_generics became stable !
/*let mut buffer = uninit_array![u8; 69];
buffer.as_out().copy_from_slice(bytes);
Ok(Self(unsafe { std::mem::transmute(buffer) }))*/
let mut buffer = [0u8; 69];
buffer.copy_from_slice(bytes);
Ok(Self(buffer))
} else {
Err(CorruptedBytes("db corrupted".to_owned()))
}
}
}
#[cfg(feature = "explorer")]
impl ExplorableKey for GvaUtxoIdDbV1 {
fn from_explorer_str(_: &str) -> std::result::Result<Self, FromExplorerKeyErr> {
unimplemented!()
}
fn to_explorer_string(&self) -> KvResult<String> {
Ok(self.to_string())
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
...@@ -252,17 +121,4 @@ mod tests { ...@@ -252,17 +121,4 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn utxo_gva_id_new() {
let script = WalletScriptV10::single(WalletConditionV10::Csv(86_400));
let script_hash = Hash::compute(script.to_string().as_bytes());
let tx_hash = Hash::default();
let utxo_gva_id = GvaUtxoIdDbV1::new(script, 42, tx_hash, 3);
assert_eq!(utxo_gva_id.get_script_hash(), script_hash);
assert_eq!(utxo_gva_id.get_block_number(), 42);
assert_eq!(utxo_gva_id.get_tx_hash(), tx_hash);
assert_eq!(utxo_gva_id.get_output_index(), 3);
}
} }
...@@ -64,16 +64,13 @@ pub use keys::source_key::SourceKeyV1; ...@@ -64,16 +64,13 @@ pub use keys::source_key::SourceKeyV1;
pub use keys::timestamp::TimestampKeyV1; pub use keys::timestamp::TimestampKeyV1;
pub use keys::ud_id::UdIdV2; pub use keys::ud_id::UdIdV2;
pub use keys::uid::UidKeyV1; pub use keys::uid::UidKeyV1;
pub use keys::utxo_id::GvaUtxoIdDbV1;
pub use keys::wallet_conditions::{WalletConditionsV1, WalletConditionsV2}; pub use keys::wallet_conditions::{WalletConditionsV1, WalletConditionsV2};
pub use keys::wallet_hash_with_bn::WalletHashWithBnV1Db;
pub use values::block_db::{BlockDbEnum, BlockDbV1, BlockDbV2, TransactionInBlockDbV1}; pub use values::block_db::{BlockDbEnum, BlockDbV1, BlockDbV2, TransactionInBlockDbV1};
pub use values::block_head_db::BlockHeadDbV1; pub use values::block_head_db::BlockHeadDbV1;
pub use values::block_meta::BlockMetaV2; pub use values::block_meta::BlockMetaV2;
pub use values::block_number_array_db::BlockNumberArrayV1; pub use values::block_number_array_db::BlockNumberArrayV1;
pub use values::cindex_db::CIndexDbV1; pub use values::cindex_db::CIndexDbV1;
pub use values::dunp_head::DunpHeadDbV1; pub use values::dunp_head::DunpHeadDbV1;
pub use values::gva_idty_db::GvaIdtyDbV1;
pub use values::idty_db::IdtyDbV2; pub use values::idty_db::IdtyDbV2;
pub use values::iindex_db::IIndexDbV1; pub use values::iindex_db::IIndexDbV1;
pub use values::kick_db::KickDbV1; pub use values::kick_db::KickDbV1;
...@@ -82,12 +79,11 @@ pub use values::peer_card::PeerCardDbV1; ...@@ -82,12 +79,11 @@ pub use values::peer_card::PeerCardDbV1;
pub use values::pubkey_db::{PubKeyValV2, PublicKeyArrayDbV1, PublicKeySingletonDbV1}; pub use values::pubkey_db::{PubKeyValV2, PublicKeyArrayDbV1, PublicKeySingletonDbV1};
pub use values::sindex_db::{SIndexDBV1, SourceKeyArrayDbV1}; pub use values::sindex_db::{SIndexDBV1, SourceKeyArrayDbV1};
pub use values::source_amount::SourceAmountValV2; pub use values::source_amount::SourceAmountValV2;
pub use values::tx_db::{PendingTxDbV2, TxDbV2}; pub use values::tx_db::PendingTxDbV2;
pub use values::txs::BlockTxsDbV2; pub use values::txs::BlockTxsDbV2;
pub use values::ud_entry_db::{ConsumedUdDbV1, UdAmountDbV1, UdEntryDbV1}; pub use values::ud_entry_db::{ConsumedUdDbV1, UdAmountDbV1, UdEntryDbV1};
pub use values::utxo::{BlockUtxosV2Db, UtxoValV2}; pub use values::utxo::{BlockUtxosV2Db, UtxoValV2};
pub use values::wallet_db::WalletDbV1; pub use values::wallet_db::WalletDbV1;
pub use values::wallet_script_array::WalletScriptArrayV2;
pub use values::wallet_script_with_sa::WalletScriptWithSourceAmountV1Db; pub use values::wallet_script_with_sa::WalletScriptWithSourceAmountV1Db;
// Crate imports // Crate imports
......
...@@ -19,7 +19,6 @@ pub mod block_meta; ...@@ -19,7 +19,6 @@ pub mod block_meta;
pub mod block_number_array_db; pub mod block_number_array_db;
pub mod cindex_db; pub mod cindex_db;
pub mod dunp_head; pub mod dunp_head;
pub mod gva_idty_db;
pub mod idty_db; pub mod idty_db;
pub mod iindex_db; pub mod iindex_db;
pub mod kick_db; pub mod kick_db;
...@@ -33,5 +32,4 @@ pub mod txs; ...@@ -33,5 +32,4 @@ pub mod txs;
pub mod ud_entry_db; pub mod ud_entry_db;
pub mod utxo; pub mod utxo;
pub mod wallet_db; pub mod wallet_db;
pub mod wallet_script_array;
pub mod wallet_script_with_sa; pub mod wallet_script_with_sa;
...@@ -50,42 +50,3 @@ impl ExplorableValue for PendingTxDbV2 { ...@@ -50,42 +50,3 @@ impl ExplorableValue for PendingTxDbV2 {
serde_json::to_value(self).map_err(|e| KvError::DeserError(e.into())) serde_json::to_value(self).map_err(|e| KvError::DeserError(e.into()))
} }
} }
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct TxDbV2 {
pub tx: TransactionDocumentV10,
pub written_block: Blockstamp,
pub written_time: i64,
}
impl AsBytes for TxDbV2 {
fn as_bytes<T, F: FnMut(&[u8]) -> T>(&self, mut f: F) -> T {
let bytes = bincode::serialize(self).unwrap_or_else(|_| unreachable!());
f(bytes.as_ref())
}
}
impl kv_typed::prelude::FromBytes for TxDbV2 {
type Err = CorruptedBytes;
fn from_bytes(bytes: &[u8]) -> std::result::Result<Self, Self::Err> {
Ok(bincode::deserialize(&bytes)
.map_err(|e| CorruptedBytes(format!("{}: '{:?}'", e, bytes)))?)
}
}
impl ToDumpString for TxDbV2 {
fn to_dump_string(&self) -> String {
todo!()
}
}
#[cfg(feature = "explorer")]
impl ExplorableValue for TxDbV2 {
fn from_explorer_str(source: &str) -> Result<Self, FromExplorerValueErr> {
Self::from_bytes(source.as_bytes()).map_err(|e| FromExplorerValueErr(e.0.into()))
}
fn to_explorer_json(&self) -> KvResult<serde_json::Value> {
serde_json::to_value(self).map_err(|e| KvError::DeserError(e.into()))
}
}
...@@ -14,6 +14,7 @@ async-trait = "0.1.41" ...@@ -14,6 +14,7 @@ async-trait = "0.1.41"
dubp = { version = "0.34.0" } dubp = { version = "0.34.0" }
duniter-conf = { path = "../../duniter-conf" } duniter-conf = { path = "../../duniter-conf" }
duniter-dbs = { path = "../../duniter-dbs" } duniter-dbs = { path = "../../duniter-dbs" }
duniter-gva-db = { path = "./db" }
duniter-gva-dbs-reader = { path = "./dbs-reader" } duniter-gva-dbs-reader = { path = "./dbs-reader" }
duniter-gva-indexer = { path = "./indexer" } duniter-gva-indexer = { path = "./indexer" }
duniter-gva-gql = { path = "./gql" } duniter-gva-gql = { path = "./gql" }
......
[package]
name = "duniter-gva-db"
version = "0.1.0"
authors = ["elois <elois@duniter.org>"]
description = "Duniter GVA DB"
repository = "https://git.duniter.org/nodes/typescript/duniter"
license = "AGPL-3.0"
edition = "2018"
[lib]
path = "src/lib.rs"
[dependencies]
bincode = "1.2.1"
chrono = { version = "0.4.15", optional = true }
duniter-dbs = { path = "../../../duniter-dbs" }
dubp = { version = "0.34.0" }
kv_typed = { path = "../../../tools/kv_typed", default-features = false, features = ["sled_backend"] }
paste = "1.0.2"
serde = { version = "1.0.105", features = ["derive"] }
serde_json = "1.0.53"
uninit = "0.4.0"
zerocopy = "0.3.0"
[dev-dependencies]
[features]
#default = ["explorer"]
explorer = ["chrono", "duniter-dbs/explorer", "kv_typed/explorer"]
leveldb_backend = ["kv_typed/leveldb_backend"]
// Copyright (C) 2020 Éloïs SANCHEZ.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pub mod gva_utxo_id;
pub mod wallet_hash_with_bn;
// Copyright (C) 2020 Éloïs SANCHEZ.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::*;
use uninit::prelude::*;
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct GvaUtxoIdDbV1([u8; 69]); // script hash ++ block_number ++ tx_hash ++ output_index
impl Default for GvaUtxoIdDbV1 {
fn default() -> Self {
GvaUtxoIdDbV1([0u8; 69])
}
}
impl std::fmt::Display for GvaUtxoIdDbV1 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}:{}:{}:{}",
self.get_script_hash(),
self.get_block_number(),
self.get_tx_hash(),
self.get_output_index()
)
}
}
impl GvaUtxoIdDbV1 {
pub fn get_script_hash(&self) -> Hash {
let mut buffer = uninit_array![u8; 32];
buffer.as_out().copy_from_slice(&self.0[..32]);
Hash(unsafe { std::mem::transmute(buffer) })
}
pub fn get_block_number(&self) -> u32 {
let mut buffer = uninit_array![u8; 4];
buffer.as_out().copy_from_slice(&self.0[32..36]);
u32::from_be_bytes(unsafe { std::mem::transmute(buffer) })
}
pub fn get_tx_hash(&self) -> Hash {
let mut buffer = uninit_array![u8; 32];
buffer.as_out().copy_from_slice(&self.0[36..68]);
Hash(unsafe { std::mem::transmute(buffer) })
}
pub fn get_output_index(&self) -> u8 {
self.0[68]
}
pub fn new(
script: WalletScriptV10,
block_number: u32,
tx_hash: Hash,
output_index: u8,
) -> Self {
let script_hash = Hash::compute(script.to_string().as_bytes());
Self::new_(script_hash, block_number, tx_hash, output_index)
}
pub fn new_(script_hash: Hash, block_number: u32, tx_hash: Hash, output_index: u8) -> Self {
// TODO uncomment when feature const_generics became stable !
/*let mut buffer = uninit_array![u8; 69];
let (hash_buffer, rest_buffer) = buffer.as_out().split_at_out(32);
let (bn_buffer, rest_buffer) = rest_buffer.split_at_out(4);
let (tx_hash_buffer, output_index_buffer) = rest_buffer.split_at_out(32);
hash_buffer.copy_from_slice(script_hash.as_ref());
bn_buffer.copy_from_slice(&block_number.to_be_bytes()[..]);
tx_hash_buffer.copy_from_slice(tx_hash.as_ref());
output_index_buffer.copy_from_slice(&[output_index]);
Self(unsafe { std::mem::transmute(buffer) })*/
let mut buffer = [0u8; 69];
buffer[..32].copy_from_slice(script_hash.as_ref());
buffer[32..36].copy_from_slice(&block_number.to_be_bytes()[..]);
buffer[36..68].copy_from_slice(tx_hash.as_ref());
buffer[68] = output_index;
Self(buffer)
}
pub fn script_interval(script_hash: Hash) -> (Self, Self) {
let mut buffer = [0; 69];
buffer[..32].copy_from_slice(script_hash.as_ref());
let min = Self(buffer);
let mut buffer = [255; 69];
buffer[..32].copy_from_slice(script_hash.as_ref());
let max = Self(buffer);
(min, max)
}
pub fn script_block_interval(
script_hash: Hash,
block_number_start: u32,
block_number_end: u32,
) -> (Self, Self) {
(
Self::new_(script_hash, block_number_start, Hash::default(), 0),
Self::new_(script_hash, block_number_end, Hash::max(), u8::MAX),
)
}
}
impl AsBytes for GvaUtxoIdDbV1 {
fn as_bytes<T, F: FnMut(&[u8]) -> T>(&self, mut f: F) -> T {
f(&self.0[..])
}
}
impl FromBytes for GvaUtxoIdDbV1 {
type Err = CorruptedBytes;
fn from_bytes(bytes: &[u8]) -> std::result::Result<Self, Self::Err> {
if bytes.len() == 69 {
// TODO uncomment when feature const_generics became stable !
/*let mut buffer = uninit_array![u8; 69];
buffer.as_out().copy_from_slice(bytes);
Ok(Self(unsafe { std::mem::transmute(buffer) }))*/
let mut buffer = [0u8; 69];
buffer.copy_from_slice(bytes);
Ok(Self(buffer))
} else {
Err(CorruptedBytes("db corrupted".to_owned()))
}
}
}
#[cfg(feature = "explorer")]
impl ExplorableKey for GvaUtxoIdDbV1 {
fn from_explorer_str(_: &str) -> std::result::Result<Self, FromExplorerKeyErr> {
unimplemented!()
}
fn to_explorer_string(&self) -> KvResult<String> {
Ok(self.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utxo_gva_id_new() {
let script = WalletScriptV10::single(WalletConditionV10::Csv(86_400));
let script_hash = Hash::compute(script.to_string().as_bytes());
let tx_hash = Hash::default();
let utxo_gva_id = GvaUtxoIdDbV1::new(script, 42, tx_hash, 3);
assert_eq!(utxo_gva_id.get_script_hash(), script_hash);
assert_eq!(utxo_gva_id.get_block_number(), 42);
assert_eq!(utxo_gva_id.get_tx_hash(), tx_hash);
assert_eq!(utxo_gva_id.get_output_index(), 3);
}
}
...@@ -13,14 +13,42 @@ ...@@ -13,14 +13,42 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::*; #![deny(
clippy::unwrap_used,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unstable_features,
unused_import_braces
)]
mod keys;
mod values;
pub use keys::gva_utxo_id::GvaUtxoIdDbV1;
pub use keys::wallet_hash_with_bn::WalletHashWithBnV1Db;
pub use values::gva_idty_db::GvaIdtyDbV1;
pub use values::gva_tx::GvaTxDbV1;
pub use values::wallet_script_array::WalletScriptArrayV2;
pub(crate) use dubp::common::prelude::*;
pub(crate) use dubp::crypto::hashs::Hash;
pub(crate) use dubp::wallet::prelude::*;
pub(crate) use duniter_dbs::smallvec::SmallVec;
pub(crate) use duniter_dbs::{
CorruptedBytes, HashKeyV2, PubKeyKeyV2, SourceAmountValV2, ToDumpString, WalletConditionsV2,
};
pub(crate) use kv_typed::db_schema;
pub(crate) use kv_typed::prelude::*;
pub(crate) use serde::{Deserialize, Serialize};
pub(crate) use std::collections::BTreeSet;
db_schema!( db_schema!(
GvaV1, GvaV1,
[ [
["blocks_with_ud", BlocksWithUd, U32BE, ()], ["blocks_with_ud", BlocksWithUd, U32BE, ()],
["blockchain_time", BlockchainTime, U32BE, u64], ["blockchain_time", BlockchainTime, U32BE, u64],
["txs", Txs, HashKeyV2, TxDbV2], ["txs", Txs, HashKeyV2, GvaTxDbV1],
["txs_by_issuer", TxsByIssuer, WalletHashWithBnV1Db, BTreeSet<Hash>], ["txs_by_issuer", TxsByIssuer, WalletHashWithBnV1Db, BTreeSet<Hash>],
["txs_by_recipient", TxsByRecipient, WalletHashWithBnV1Db, BTreeSet<Hash>], ["txs_by_recipient", TxsByRecipient, WalletHashWithBnV1Db, BTreeSet<Hash>],
[ [
......
// Copyright (C) 2020 Éloïs SANCHEZ.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pub mod gva_idty_db;
pub mod gva_tx;
pub mod wallet_script_array;
// Copyright (C) 2020 Éloïs SANCHEZ.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::*;
use dubp::documents::transaction::TransactionDocumentV10;
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct GvaTxDbV1 {
pub tx: TransactionDocumentV10,
pub written_block: Blockstamp,
pub written_time: i64,
}
impl AsBytes for GvaTxDbV1 {
fn as_bytes<T, F: FnMut(&[u8]) -> T>(&self, mut f: F) -> T {
let bytes = bincode::serialize(self).unwrap_or_else(|_| unreachable!());
f(bytes.as_ref())
}
}
impl kv_typed::prelude::FromBytes for GvaTxDbV1 {
type Err = CorruptedBytes;
fn from_bytes(bytes: &[u8]) -> std::result::Result<Self, Self::Err> {
Ok(bincode::deserialize(&bytes)
.map_err(|e| CorruptedBytes(format!("{}: '{:?}'", e, bytes)))?)
}
}
impl ToDumpString for GvaTxDbV1 {
fn to_dump_string(&self) -> String {
todo!()
}
}
#[cfg(feature = "explorer")]
impl ExplorableValue for GvaTxDbV1 {
fn from_explorer_str(source: &str) -> Result<Self, FromExplorerValueErr> {
Self::from_bytes(source.as_bytes()).map_err(|e| FromExplorerValueErr(e.0.into()))
}
fn to_explorer_json(&self) -> KvResult<serde_json::Value> {
serde_json::to_value(self).map_err(|e| KvError::DeserError(e.into()))
}
}
...@@ -14,7 +14,6 @@ ...@@ -14,7 +14,6 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::*; use crate::*;
#[derive(Debug, Default, PartialEq)] #[derive(Debug, Default, PartialEq)]
pub struct WalletScriptArrayV2(pub std::collections::HashSet<WalletScriptV10>); pub struct WalletScriptArrayV2(pub std::collections::HashSet<WalletScriptV10>);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment