dbpunk-labs / db3 Goto Github PK
View Code? Open in Web Editor NEWa Lightweight, Permanent JSON document database
Home Page: https://docs.db3.network/
License: Apache License 2.0
a Lightweight, Permanent JSON document database
Home Page: https://docs.db3.network/
License: Apache License 2.0
Current most of dapps use centralized database to store user data and use arweave as a decentralized backup, Now we want use
db3 to replace arweave.
We can split this issue into two steps
step 1, use rust sdk to execute SQL. Resolved by dbpunk-labs/substrate-api-client#1
step2 ,subscribe mysql binlog and write all data to db3. dbpunk-labs/substrate-api-client#2
Web3 native applications need a decentralized data architecture, but it's not easy to build a fully decentralized data architecture, for web3 startups MySQL is still the first option, but MySQL is a centralized data architecture and then they have to take a lot of time to develop tools to synchronize partial data of MySQL to arweave
db3_cdc can help web3 developers to setup synchronizing all data of MySQL to DB3 out of box
if you are looking for a fully decentralized data architecture, you can use db3 directly
wget https://github.com/dbpunk-labs/db3cdc/releases/download/v0.2.0/db3cdc-v0.2.0-linux-x86_64.tar.gz
tar -zxf db3cdc-v0.2.0-linux-x86_64.tar.gz
cd ./db3cdc-v0.2.0-linux-x86_64/
./bin/db3cdc --help
Usage: db3cdc <COMMAND>
Commands:
sync Start a interactive shell
version Get the version of DB3 CDC
help Print this message or the help of the given subcommand(s)
Options:
-h, --help Print help information
./bin/db3cdc sync --db3-node-grpc-url https://grpc.devnet.db3.network\
--password mysql_password \
--user mysql_root_user \
--master-host mysql_host \
--master-port mysql_port
the devnet is unstable, you can change the grpc url to the following nodes in our testnet
2022-11-21T04:47:29.038953Z INFO db3cdc: no gtid state in db3
WARNING, db3 will generate private key and save it to /home/jackwang/.db3/user.key
restore the key with addr 0x97b478ac2bef8762c2ecc08417f35838c4bf73fc
2022-11-21T04:47:29.040835Z INFO db3cdc: binlog options BinlogOptions { filename: "", position: 4, gtid_set: None, gtid_list: None, starting_strategy: FromStart }
2022-11-21T04:47:29.349037Z INFO db3cdc: mutation id "tWYRruF8dSwvOySMypYCD0pJTVZgquKZu116UddTAps="
2022-11-21T04:47:29.429778Z INFO db3cdc: Your account 0x97b478ac2bef8762c2ecc08417f35838c4bf73fc status: total bills 0.000000 db3, total storage used 0.00 , total mutation 0, credits 10 db3
these information includes
?
Error: The process '/home/runner/.cargo/bin/cargo' failed with exit code 1
Run actions-rs/cargo@v1
/home/runner/.cargo/bin/cargo fmt --all -- --check
`cargo metadata` exited with an error: error: failed to load manifest for workspace member `/home/runner/work/db3/db3/rpc`
Caused by:
failed to load manifest for dependency `db3-primitives`
Caused by:
failed to load manifest for dependency `frame-system`
Caused by:
failed to read `/home/runner/work/db3/db3/thirdparty/substrate/frame/system/Cargo.toml`
Caused by:
No such file or directory (os error 2)
cargo-fmt
This utility formats all bin and lib files of the current crate using rustfmt.
USAGE:
cargo fmt [OPTIONS] [-- <rustfmt_options>...]
ARGS:
<rustfmt_options>... Options passed to rustfmt
OPTIONS:
--all
Format all packages, and also their local path-based dependencies
--check
Run rustfmt in check mode
-h, --help
Print help information
--manifest-path <manifest-path>
Specify path to Cargo.toml
--message-format <message-format>
Specify message-format: short|json|human
-p, --package <package>...
Specify package to format
-q, --quiet
No output printed to stdout
-v, --verbose
Use verbose output
--version
Print rustfmt version and exit
Error: The process '/home/runner/.cargo/bin/cargo' failed with exit code 1
Steps to reproduce the behavior:
use mysql cli to create a table
mysql -h 127.0.0.1 -p 3306 -u root -P
>create database eth;
>use eth;
>create table price{
ts timestamp,
price double
};
>insert into price value('2022-12-10 01-01', 1000);
>select * from price limit 1;
let‘s look at the method eth_getBlockByHash
from etherum openrpc.json
name | type |
---|---|
parentHash | string |
sha3Uncles | string |
miner | string |
stateRoot | string |
transactionsRoot | string |
receiptsRoot | string |
receiptsRoot | string |
transactions | array |
number | string |
... | ... |
select timestamp, miner, number from block where number in (15044280);
this sql will call json rpc
call eth_getBlockByNumber(15044280)
do some process
select date(`timestamp`), miner, number from block where number in (15044280);
select * from Values (select block.transactions where number in (15044280));
let ctx = SessionContext::new();
let path = format!("{}/2.json", TEST_DATA_BASE);
ctx.register_json("t1", &path, NdJsonReadOptions::default())
.await
.unwrap();
let sql = "SELECT a, b FROM t1";
let actual = execute_to_batches(&ctx, sql).await;
let expected = vec![
"+-----------------+------+",
"| a | b |",
"+-----------------+------+",
"| 1 | 2 |",
"| -10 | -3.5 |",
"| 2 | 0.6 |",
"| 1 | 2 |",
"| 7 | -3.5 |",
"| 1 | 0.6 |",
"| 1 | 2 |",
"| 5 | -3.5 |",
"| 1 | 0.6 |",
"| 1 | 2 |",
"| 1 | -3.5 |",
"| 100000000000000 | 0.6 |",
"+-----------------+------+",
];
assert_batches_eq!(expected, &actual);
protoc-gen-js: program not found or is not executable
Please specify a program using absolute path or make sure the program is available in your PATH system variable
--js_out: protoc-gen-js: Plugin failed with status code 1.
protoc version: 3.21.9
Currently, db3 uses merk as merkled index storage engine.
the advantage of merk
the shortcomings
the unsupported feature that db3 needs
the namespaced Merkle tree is proposed by Celestia in the LazyLedger academic paper.so I want to propose a new merkled index storage engine called merkdb based on merk and merkdb has the following improvements
and you can consider merkdb as rocksdb in crypto
Move all libraries to src dir
Support req_id in the newly added pallet calls API
sync onchain data node to timeseries store
# start rtstore
docker run -p 9292:9292 -dt ghcr.io/rtstore/rtstore:0.1.0
# use cli to connect to rtstore
mysql -h localhost -P 9292 -u root
# create tables
>create tables WITH ("blocknode_urls"="ws://xxxx","contract"="0x0a267cF51EF038fC00E71801F5a524aec06e4f07", "blockchain"="eth","auto_gen"="true");
# analysis the data
> select * from xxx_event limit1;
Caused by:
process didn't exit successfully: `/home/runner/work/db3/db3/target/llvm-cov-target/debug/build/substrate-test-runtime-3dc7e40855a606a9/build-script-build` (exit status: 1)
--- stderr
Rust WASM toolchain not installed, please install it!
Further error information:
------------------------------------------------------------
Compiling wasm-test v1.0.0 (/tmp/.tmpbRfrOO)
error[E0463]: can't find crate for `std`
|
= note: the `wasm32-unknown-unknown` target may not be installed
= help: consider downloading the target with `rustup target add wasm32-unknown-unknown`
= help: consider building the standard library from source with `cargo build -Zbuild-std`
error: cannot find macro `println` in this scope
--> src/main.rs:3:5
|
3 | println!("{}", env!("RUSTC_VERSION"));
| ^^^^^^^
error: requires `sized` lang_item
For more information about this error, try `rustc --explain E0463`.
error: could not compile `wasm-test` due to 3 previous errors
------------------------------------------------------------
Steps to reproduce the behavior:
Initialize a development environment based on tendermint-rs
put a key to kvstore and get value from kvstore
Etcd Path rules for rtstore
/rtstore
|
\_tables/test.eth -> data // store meta for table
|
\_nodes_0/127.0.0.1_8989 -> data // store meta for frontend node
|
\_nodes_1/127.0.0.1_9191 -> data // store meta for meta node
|
\_nodes_2/127.0.0.1_9292 -> data // store meta for memory node
|
\_nodes_3/127.0.0.1_7979 -> data // store meta for compute node
let the frontend to handle response easily
GeneralResultEvent (Vec<u8>)
the data in GeneralResultEvent is a json string like
{
"status": 0,
"msg":"xxxx",
"schema":"xx",
"data":{},
"req_id":""
}
Steps to reproduce the behavior:
cargo build --package db3-runtime --release
build package successfully
error[E0405]: cannot find trait `DBAccountApi` in crate `sqldb_rpc_runtime_api`
--> runtime/src/lib.rs:1936:33
|
1936 | impl sqldb_rpc_runtime_api::DBAccountApi<Block, AccountId> for Runtime {
| ^^^^^^^^^^^^ not found in `sqldb_rpc_runtime_api`
|
help: consider importing this trait
|
25 | use sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi::DBAccountApi;
|
help: if you import `DBAccountApi`, refer to it directly
|
1936 - impl sqldb_rpc_runtime_api::DBAccountApi<Block, AccountId> for Runtime {
1936 + impl DBAccountApi<Block, AccountId> for Runtime {
|
error[E0425]: cannot find function `is_ns_owner_call_api_at` in module `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
--> runtime/src/lib.rs:1774:1
|
1774 | / impl_runtime_apis! {
1775 | | impl sp_api::Core<Block> for Runtime {
1776 | | fn version() -> RuntimeVersion {
1777 | | VERSION
... |
2169 | | }
2170 | | }
| |_^ not found in `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
|
= note: this error originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0425]: cannot find function `is_ns_owner_native_call_generator` in module `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
--> runtime/src/lib.rs:1774:1
|
1774 | / impl_runtime_apis! {
1775 | | impl sp_api::Core<Block> for Runtime {
1776 | | fn version() -> RuntimeVersion {
1777 | | VERSION
... |
2169 | | }
2170 | | }
| |_^ not found in `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
|
= note: this error originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0425]: cannot find function `list_delegates_call_api_at` in module `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
--> runtime/src/lib.rs:1774:1
|
1774 | / impl_runtime_apis! {
1775 | | impl sp_api::Core<Block> for Runtime {
1776 | | fn version() -> RuntimeVersion {
1777 | | VERSION
... |
2169 | | }
2170 | | }
| |_^ not found in `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
|
= note: this error originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0425]: cannot find function `list_delegates_native_call_generator` in module `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
--> runtime/src/lib.rs:1774:1
|
1774 | / impl_runtime_apis! {
1775 | | impl sp_api::Core<Block> for Runtime {
1776 | | fn version() -> RuntimeVersion {
1777 | | VERSION
... |
2169 | | }
2170 | | }
| |_^ not found in `sqldb_rpc_runtime_api::runtime_decl_for_DBAccountApi`
|
= note: this error originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)
Some errors have detailed explanations: E0405, E0425.
For more information about an error, try `rustc --explain E0405`.
error: could not compile `db3-runtime` due to 5 previous errors
the method list
how to return reqid?
add reqid to event that will be returned to frontent
the concept of query session
Move all functions for mysql to frontend node
Make the compute node has not any logical for frontend node
for mysql compatible
Avoid db3 to lost data in the system page cache
Currently, only SIGKILL can be used to shutdown db3 and it's better to use SIGTERM to stop db3
the Javascript SDK needs to broadcast mutations to the DB3 network
WriteRequest
WriteRequest
to Uint8Arraysample rust code
let json_rpc_url = "http://127.0.0.1:26670";
let client = awc::Client::default();
let kp = db3_cmd::get_key_pair(false).unwrap();
let signer = Db3Signer::new(kp);
let kv = KvPair {
key: format!("kkkkk_tt{}", 1).as_bytes().to_vec(),
value: format!("vkalue_tt{}", 1).as_bytes().to_vec(),
action: MutationAction::InsertKv.into(),
};
let mutation = Mutation {
ns: "my_twitter".as_bytes().to_vec(),
kv_pairs: vec![kv],
nonce: 1110,
chain_id: ChainId::MainNet.into(),
chain_role: ChainRole::StorageShardChain.into(),
gas_price: None,
gas: 10,
};
let mut mbuf = BytesMut::with_capacity(1024 * 4);
mutation.encode(&mut mbuf).unwrap();
let mbuf = mbuf.freeze();
let signature = signer.sign(mbuf.as_ref()).unwrap();
let request = WriteRequest {
signature,
mutation: mbuf.as_ref().to_vec().to_owned(),
};
let mut buf = BytesMut::with_capacity(1024 * 4);
request.encode(&mut buf).unwrap();
let buf = buf.freeze();
// encode request to base64
let data = base64::encode(buf.as_ref());
let base64_str = String::from_utf8_lossy(data.as_ref()).to_string();
let request = serde_json::json!(
{"method": "broadcast",
"params": vec![base64_str],
"id": 1,
"jsonrpc": "2.0"
}
);
let mut response = client.post(json_rpc_url).send_json(&request).await.unwrap();
if let serde_json::Value::Object(val) = response.json::<serde_json::Value>().await.unwrap() {
if let Some(serde_json::Value::String(s)) = val.get("result") {
assert!(s.len() > 0);
}else {
assert!(false)
}
}else {
assert!(false)
}
WriteRequest
WriteRequest
to Uint8Arraysample request
curl --header "Content-Type: application/json" --request POST --data '{"method": "broadcast", "params": ["XADAFA="], "id": 1, "jsonrpc": "2.0"}' localhost:26670
Note
: you must replace the params with valid one
sample response
{"id": 1, "jsonrpc": "2.0", "result": "bDJ9tsALNX42gR6UZ8+q/xh5hoacShtKcZj5mxeAmhU="}
this PR #151 has done some work
git clone [email protected]:dbpunk-labs/db3.git -b 149-support-submitting-mutation-in-json-rpc
cd db3 && cargo build && cd tools && bash start_localnet.sh
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.