Skip to content

Commit

Permalink
Merge pull request #43 from commerceblock/develop
Browse files Browse the repository at this point in the history
Release 0.3.9 - Enhancements
  • Loading branch information
Nikos Kostoulas authored Oct 30, 2019
2 parents 802cacb + bdca8be commit 87c6b42
Show file tree
Hide file tree
Showing 21 changed files with 925 additions and 682 deletions.
2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
format_strings = true
wrap_comments = true
format_doc_comments = true
format_code_in_doc_comments = true
merge_imports = false
max_width = 120
508 changes: 246 additions & 262 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion config/default.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ pass = "password1"
host = "127.0.0.1:5555"
user = "user1"
pass = "password1"
asset_hash = "93fed59e9407ddc47993fc176a245383eb2a5c06c265ce0e02ff2b59da44f439"
genesis_hash = "ff8950160a77988cdc485913568d06c2d69a8c952ef0f179b4b097e3de63d7cc"
asset = "CHALLENGE"
asset_key = "cScSHCQp9AEwzZoucRpX9bMRkLCJ4LoQWBNFTZuD6tPX9qwNMWfQ"
Expand Down
3 changes: 1 addition & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ services:
CO_CLIENTCHAIN_HOST: client_chain:5555
CO_CLIENTCHAIN_USER: user1
CO_CLIENTCHAIN_PASS: password1
CO_CLIENTCHAIN_ASSET_HASH: fae9f771019d45e31b8f78da99a15b094b17b2ba76b0940c3ac53d5e9afd8e8e
CO_CLIENTCHAIN_GENESIS_HASH: d1fbd07bd9a7a80a85445b8e28246f0b644c01ac7412e81ce3ffc0815386ad77
CO_CLIENTCHAIN_ASSET_KEY: cScSHCQp9AEwzZoucRpX9bMRkLCJ4LoQWBNFTZuD6tPX9qwNMWfQ

Expand All @@ -59,4 +58,4 @@ networks:
driver: bridge
ipam:
config:
- subnet: 192.168.12.0/24
- subnet: 192.168.12.0/24
22 changes: 16 additions & 6 deletions examples/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use hyper::{
use ocean_rpc::RpcApi;
use secp256k1::{Message, Secp256k1, SecretKey};

use coordinator::clientchain::get_first_unspent;
use coordinator::coordinator as coordinator_main;
use coordinator::ocean::OceanClient;

Expand Down Expand Up @@ -50,32 +51,35 @@ fn main() {
// auto client chain block generation
let client_rpc_clone = client_rpc.clone();
thread::spawn(move || loop {
thread::sleep(time::Duration::from_secs(10));
thread::sleep(time::Duration::from_secs(5));
if let Err(e) = client_rpc_clone.clone().client.generate(1) {
error!("{}", e);
}
});

let genesis_hash = sha256d::Hash::from_hex(&config.clientchain.genesis_hash).unwrap();
let request_txid = &client_rpc.get_requests(Some(&genesis_hash)).unwrap()[0].txid;
let request = &client_rpc.get_requests(Some(&genesis_hash));
if request.as_ref().unwrap().is_empty() {
panic!("No active request in client blockchain!")
}
let request_txid = request.as_ref().unwrap()[0].txid;
let guardnode_pubkey = "026a04ab98d9e4774ad806e302dddeb63bea16b5cb5f223ee77478e861bb583eb3";
let mut guardnode_txid = genesis_hash; // dummy init
for bid in client_rpc.get_request_bids(request_txid).unwrap().unwrap().bids {
for bid in client_rpc.get_request_bids(&request_txid).unwrap().unwrap().bids {
if bid.fee_pub_key.to_string() == guardnode_pubkey {
guardnode_txid = bid.txid;
println!("guardnode bid txid: {}", guardnode_txid);
break;
}
}

// add two guardnodes with valid keys and one without
// keys based on mockservice request bids
let asset_hash = config.clientchain.asset_hash.clone();
let listener_host = config.listener_host.clone();
let client_rpc_clone = client_rpc.clone();
thread::spawn(move || {
guardnode(
&client_rpc_clone,
sha256d::Hash::from_hex(&asset_hash).unwrap(),
listener_host.clone(),
guardnode_txid,
SecretKey::from_slice(&[0xaa; 32]).unwrap(),
Expand All @@ -92,14 +96,20 @@ fn main() {
/// Bid info (key/txid) are based on MockService data for demo purpose
fn guardnode(
client_rpc: &OceanClient,
asset_hash: sha256d::Hash,
listener_host: String,
guard_txid: sha256d::Hash,
guard_key: SecretKey,
guard_pubkey: String,
) {
let secp = Secp256k1::new();
let mut prev_block_count = 0;
// Get asset hash from unspent list
let asset_hash;
match get_first_unspent(&client_rpc, &String::from("CHALLENGE")) {
Err(_) => panic!("No challenge asset issued in client blockchain!"),
Ok(res) => asset_hash = res.asset,
}

loop {
if let Ok(block_count) = client_rpc.get_block_count() {
if block_count > prev_block_count {
Expand Down
Empty file modified scripts/authproxy.py
100644 → 100755
Empty file.
155 changes: 155 additions & 0 deletions scripts/create_request.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
#!/bin/bash
shopt -s expand_aliases
alias ocl="$HOME/jsonrpc-cli/jsonrpc-cli --user=$RPC_USER --pass=$RPC_PASS --format=jsonpretty --resultonly=on --highlight=off http://$RPC_CONNECT:$RPC_PORT/"
# parameters:
# $1 Genesis hash
# $2 start price
# $3 end price
# $4 auction duration
# $5 request duration
# $6 number of tickets
# $7 fee percentage
# $8 Permission asset private key
# OPTIONAL
# $9 prevtxid
# $10 prevvout

# Check parameters are set
if [ -z $1 ] || [ -z $2 ] || [ -z $3 ] || [ -z $4 ] || [ -z $5 ] || [ -z $6 ] || [ -z $7 ]
then
printf "%s\n" "createRequest genesisHash startPrice endPrice auctionDuration requestDuration numTickets feePercentage privKey ( txid ) ( vout )" \ \
"Script builds, signs and sends a request transaction to service chain." \
"Set shell enviroment variables RPC_CONNECT, RPC_PORT, RPC_USER, RPC_PASS with network connection information." \
"By deflault a TX_LOCKED_MULTISIG transaction or standard permission asset unspent output is spent to fund the request. If a specific permission asset transaction should be used then set parameters 9 and 10 accordingly." \
\ \
"Arguments:" \
"1. \"Genesis hash\" (Hex string, Required) Hash of client chain genesis block" \
"2. \"StartPrice\" (Amount, Required) Starting auction price of tickets" \
"3. \"endPrice\" (Amount, Required) Ending auction price of tickets" \
"4. \"auctionDuration\" (Integer, Required) Number of blocks auction to last for" \
"5. \"requestDuration\" (Integer, Required) Number of blocks service period to last for" \
"6. \"numTickets\" (Integer, Required) Number of tickets to be sold" \
"7. \"feePercentage\" (Integer, Required) Percentage of fee to go towards rewarding guardnodes" \
"8. \"privKey\" (String (hex), Optional) Hex encoded private key of address with permission asset" \
"9. \"txid\" (String (hex), Optional) Specified previous request transaction ID to fund new request" \
"10. \"vout\" (Integer, Optional) Specified previous request vout to fund new request"
\ \
"Result: " \
"\"txid\" (hex string) Transaction ID of request transaction"
exit
fi

# check start price > end price
if [ $2 -lt $3 ]; then
printf "Input parameter error: Start price must be larger than end price."
exit
fi
# Client chain genesis block hash
genesis=$1
# check for currently active request for given genesis hash
if [[ `ocl getrequests | jq "if .[].genesisBlock == \"$genesis\" then 1 else 0 end"` == *"1"* ]]; then
printf "Input parameter error: Genesis hash already in active request list. Relevant request info below.\n\n"
echo "Current block height: " `ocl getblockcount`
ocl getrequests $1 | jq '.[]'
exit
fi

# Request start height = current height + auction duration
currentblockheight=`ocl getblockchaininfo | jq ".blocks"`
let start=$currentblockheight+$5
# Request end height = request start height + request duration
let end=start+$4

# Starting price
price=$2
# Decay constant formula
decay=$(echo "$4^3/((1+$4)*(($2/$3)-1))" | bc)
# Number of tickets
tickets=$6
# Fee percentage paid
fee=$7

unspent=`ocl listunspent '[1, 9999999, [], true, "PERMISSION"]' | jq -c '.[]'`
# Import private key. Check if list unspent is empty first to avoid unnessesary re-scanning every time script runs
if [ ! -z $8 ] && [[ -z $unspent ]]; then
echo "Importing private key..."
ocl importprivkey $8 > /dev/null
unspent=`ocl listunspent '[1, 9999999, [], true, "PERMISSION"]' | jq -c '.[]'`
fi

checkLockTime () {
if [[ $currentblockheight -gt `echo $1 | jq -r '.locktime'` ]]; then
return 0
fi
return 1
}
# Check for specified previous request transaction info and set txid, vout variables accordingly
if [ -n "$9" ] || [ -n "${10}" ]; then
if [ -z $9 ] || [ -z ${10} ]; then
printf "Input parameter error: txid and vout must be provided for previous request transaction.\n"
exit
fi
txid=$9
vout=$10
tx=`ocl decoderawtransaction $(ocl getrawtransaction $txid)`
if checkLockTime "$tx"; then
value=`echo $tx | jq -r '.vout[0].value'`
else
printf "Input parameter error: Previous request transaction nlocktime not met.\n"
exit
fi
else
# Get previously locked TX_LOCKED_MULTISIG unspent output
for i in $unspent;
do
if [ `echo $i | jq ".solvable"` = "false" ]; then
txid=`echo $i | jq -r ".txid"`
tx=`ocl decoderawtransaction $(ocl getrawtransaction $txid | jq -r '.')`
if checkLockTime "$tx"; then
value=`echo $tx | jq -r '.vout[0].value'` # TX_LOCKED_MULTISIG permission
vout=0 # asset always vout=0
break
fi
fi
done
# If value not set yet then get standard permission asset unspent output
if [ -z $value ]; then
for i in $unspent;
do
txid=`echo $i | jq -r ".txid"`
tx=`ocl decoderawtransaction $(ocl getrawtransaction $txid | jq -r '.')`
if checkLockTime "$tx";
then
value=`echo $i | jq -r ".amount"`
vout=`echo $i | jq ".vout"`
break
fi
done
fi
if [[ ${#unspent[0]} = 4 || -z $txid ]]; then # unspent or txid is null
printf "Error: No unspent TX_LOCKED_MULTISIG or permission asset transaction outputs available in wallet.\n"
exit
fi
fi
# Address permission tokens will be locked in
pub=`ocl validateaddress $(ocl getnewaddress | jq -r '.') | jq -r ".pubkey"`

# Generate and sign request transaction
inputs="{\"txid\":\"$txid\",\"vout\":$vout}"
outputs="{\"decayConst\":$decay,\"endBlockHeight\":$end,\"fee\":$fee,\"genesisBlockHash\":\"$genesis\",\
\"startBlockHeight\":$start,\"tickets\":$tickets,\"startPrice\":$price,\"value\":$value,\"pubkey\":\"$pub\"}"

rawtx=`ocl createrawrequesttx '['$(echo $inputs)','$(echo $outputs)']' | jq -r '.'`
signedrawtx=`ocl signrawtransaction $rawtx`

# Catch signing error
if [ `echo $signedrawtx | jq ".complete"` = "false" ]; then
echo "Signing error: Script cannot be signed. Is the input transaction information correct and is it unlockable now?"
fi

txid=`ocl sendrawtransaction $(echo $signedrawtx | jq -r ".hex") | jq -r '.'`
echo "Request txid: $txid"

# Import spending address to allow script to automatically update request
address=`ocl decoderawtransaction $(echo $signedrawtx | jq -r '.hex') | jq -r '.vout[0].scriptPubKey.hex'`
ocl importaddress $address > /dev/null
65 changes: 41 additions & 24 deletions scripts/demo.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,12 @@ printf '%s\n' '#!/bin/sh' 'rpcuser=user1' \
'challengecoinsdestination=76a914be70510653867b1c648b43cfb3b0edf8420f08d788ac' > ~/co-client-dir/ocean.conf

ocd
sleep 5
sleep 8

echo "Importing challenger key"
ocl importprivkey cScSHCQp9AEwzZoucRpX9bMRkLCJ4LoQWBNFTZuD6tPX9qwNMWfQ
sleep 2

# Issue asset for bid creation
echo "Issue asset for guardnodes"
asset=`ocl issueasset 500 0`
asset_hash=`echo $asset | jq -r ".asset"`

echo "Issue another asset for guardnodes"
asset=`ocl issueasset 100 0`
asset_hash2=`echo $asset | jq -r ".asset"`

# Create request
echo "Create request"
pub=`ocl validateaddress $(ocl getnewaddress) | jq -r ".pubkey"`
Expand All @@ -52,22 +43,35 @@ outputs="{\"decayConst\":1000,\"endBlockHeight\":10,\"fee\":3,\"genesisBlockHash
\"startBlockHeight\":5,\"tickets\":2,\"startPrice\":50,\"value\":$value,\"pubkey\":\"$pub\"}"

signedtx=`ocl signrawtransaction $(ocl createrawrequesttx $inputs $outputs)`
txid=`ocl sendrawtransaction $(echo $signedtx | jq -r ".hex")`
request_txid=`ocl sendrawtransaction $(echo $signedtx | jq -r ".hex")`

ocl generate 1
ocl getrequests

# Create bid
echo "Create request bid"

# Create tx for bid to spend from
bid_txid=$(ocl sendtoaddress `ocl getnewaddress` 100 "" "" false "CBT")
ocl generate 1

addr=`ocl getnewaddress`
pub=`ocl validateaddress $addr | jq -r ".pubkey"`
unspent=`ocl listunspent 1 9999999 [] true $asset_hash | jq .[0]`
value=`echo $unspent | jq -r ".amount"`

inputs="[{\"txid\":$(echo $unspent | jq ".txid"),\"vout\":$(echo $unspent | jq -r ".vout"),\"asset\":\"$asset_hash\"}]"
outputs="{\"endBlockHeight\":10,\"requestTxid\":\"$txid\",\"pubkey\":\"$pub\",\
bid_tx=$(ocl decoderawtransaction `ocl getrawtransaction $bid_txid`)
value=$(echo $bid_tx | jq '.vout[0].value')
if [ $value = 100 ] # Find correct vout
then
vout=$(echo $bid_tx | jq '.vout[0].n')
else
vout=$(echo $bid_tx | jq '.vout[1].n')
fi
domain_asset=$(echo $bid_tx | jq '.vout['$vout'].asset')


inputs="[{\"txid\":\"$bid_txid\",\"vout\":$vout,\"asset\":$domain_asset}]"
outputs="{\"endBlockHeight\":10,\"requestTxid\":\"$request_txid\",\"pubkey\":\"$pub\",\
\"feePubkey\":\"026a04ab98d9e4774ad806e302dddeb63bea16b5cb5f223ee77478e861bb583eb3\",\
\"value\":50,\"change\":449.999,\"changeAddress\":\"$addr\",\"fee\":0.001}"
\"value\":55,\"change\":\"44.999\",\"changeAddress\":\"$addr\",\"fee\":0.001}"

signedtx=`ocl signrawtransaction $(ocl createrawbidtx $inputs $outputs)`
txid=`ocl sendrawtransaction $(echo $signedtx | jq -r ".hex")`
Expand All @@ -78,19 +82,32 @@ ocl importprivkey cPjJhtAgmbkovqCd1BgnY2nxGftX2tqen6UzaMxvFeH8xT3PWUod
sleep 2

echo "Create another request bid"
# Create tx for bid to spend from
bid_txid2=$(ocl sendtoaddress `ocl getnewaddress` 100 "" "" false "CBT")
ocl generate 1

addr=`ocl getnewaddress`
pub=`ocl validateaddress $addr | jq -r ".pubkey"`
unspent=`ocl listunspent 1 9999999 [] true $asset_hash2 | jq .[0]`
value=`echo $unspent | jq -r ".amount"`

inputs="[{\"txid\":$(echo $unspent | jq ".txid"),\"vout\":$(echo $unspent | jq -r ".vout"),\"asset\":\"$asset_hash2\"}]"
outputs="{\"endBlockHeight\":10,\"requestTxid\":\"$txid\",\"pubkey\":\"$pub\",\
\"feePubkey\":\"029aaa76fcf7b8012041c6b4375ad476408344d842000087aa93c5a33f65d50d92\",\
\"value\":50,\"change\":49.999,\"changeAddress\":\"$addr\",\"fee\":0.001}"
bid_tx=$(ocl decoderawtransaction `ocl getrawtransaction $bid_txid2`)
value=$(echo $bid_tx | jq '.vout[0].value')
if [ $value = 100 ]
then
vout=$(echo $bid_tx | jq '.vout[0].n')
else
vout=$(echo $bid_tx | jq '.vout[1].n')
fi
domain_asset=$(echo $bid_tx | jq '.vout['$vout'].asset')

inputs="[{\"txid\":\"$bid_txid2\",\"vout\":$vout,\"asset\":$domain_asset}]"
outputs="{\"endBlockHeight\":10,\"requestTxid\":\"$request_txid\",\"pubkey\":\"$pub\",\
\"feePubkey\":\"026a04ab98d9e4774ad806e302dddeb63bea16b5cb5f223ee77478e861bb583eb3\",\
\"value\":55,\"change\":\"44.999\",\"changeAddress\":\"$addr\",\"fee\":0.001}"

signedtx=`ocl signrawtransaction $(ocl createrawbidtx $inputs $outputs)`
txid=`ocl sendrawtransaction $(echo $signedtx | jq -r ".hex")`

echo "mempool"
ocl getrawmempool
ocl generate 1
ocl getrequestbids $(ocl getrequests | jq -r ".[].txid")
echo "Guardnode txid: $txid"
Empty file modified scripts/query.js
100644 → 100755
Empty file.
Loading

0 comments on commit 87c6b42

Please sign in to comment.