Skip to content

Commit

Permalink
Fix sample and use local oracle
Browse files Browse the repository at this point in the history
  • Loading branch information
Tibo-lg committed Feb 5, 2024
1 parent 943b76a commit e30cca5
Show file tree
Hide file tree
Showing 12 changed files with 263 additions and 14 deletions.
14 changes: 14 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,17 @@ jobs:
run: RUST_BACKTRACE=1 ${{ matrix.tests }} --ignored
- name: Stop bitcoin node
run: ./scripts/stop_node.sh
sample_test:
name: sample-test
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v2
- name: Start environment
run: docker-compose --profile oracle up -d
- name: Wait for container to run
run: ./scripts/wait_for_container.sh oracle-server
- name: Wait for electrs to be ready
run: ./scripts/wait_for_electrs.sh
- name: Run test
run: cargo test -- --ignored sample
41 changes: 41 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,47 @@ services:
- bitcoind-data:/home/bitcoin/.bitcoin
ports:
- 3004:3004
oracle-server:
image: ghcr.io/p2pderivatives/oracle:v0.2.3
profiles: [oracle]
command: |
-config /config
-appname p2pdoracle
-e integration
-migrate
environment:
- P2PDORACLE_DATABASE_HOST=oracle-db
- P2PDORACLE_ORACLE_KEYFILE=/key/key.pem
- P2PDORACLE_ORACLE_KEYPASS_FILE=/key/pass.txt
restart: always
depends_on:
- oracle-db
ports:
- 8080:8080
volumes:
- ./testconfig/oracle:/config
- ./testconfig/oracle/certs/oracle:/key

oracle-db:
image: "postgres:12.2"
profiles: [oracle]
command: |
-c log_statement=all
-c ssl=on
-c ssl_cert_file=/certs/db.crt
-c ssl_key_file=/certs/db.key
restart: always
ports:
- 5432:5432
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=1234
- POSTGRES_DB=db
volumes:
- oracle-db-data:/var/lib/postgresql/data/ # persist data even if container shuts down
- ./testconfig/oracle/certs/db:/certs


volumes:
bitcoind-data:
oracle-db-data:
6 changes: 6 additions & 0 deletions sample/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,9 @@ serde_json = "1.0"
serde_yaml = "0.9.14"
time = "0.3.16"
tokio = {version = "1.5", features = ["io-util", "macros", "rt", "rt-multi-thread", "sync", "net", "time"]}

[dev-dependencies]
assert_cmd = "2.0.12"
bitcoin-test-utils = { path = "../bitcoin-test-utils" }
predicates = "3.0.3"
rexpect = "0.5.0"
8 changes: 5 additions & 3 deletions sample/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ Example configurations and contract input are available in the [examples](./exam

## Quick run

To give a quick try to this sample, run the following set of commands (assuming that the working directory is the one in which this readme is located and that docker or podman is available on your machine):
To give a quick try to this sample, run the following set of commands (assuming that the working directory is the one in which this readme is located and that docker and docker-compose is available on your machine):

```bash
../scripts/start_node.sh
docker-compose --profile oracle up -d
../scripts/create_wallets.sh
cargo run ./examples/configurations/alice.yml
```
Expand All @@ -21,6 +21,8 @@ In a different terminal:
cargo run ./examples/configurations/bob.yml
```

Update the [example contract](./examples/contracts/numerical_contract_input.json#L82) replacing the number after `btcusd` with a unix timestamp sometimes in the future (this will correspond to the contract maturity date).

### On chain DLC

From the second instance (Bob), type:
Expand Down Expand Up @@ -114,4 +116,4 @@ In the other terminal, use the `listrenewchanneloffers` to display the received
To accept the offer, use the `acceptrenewchanneloffer` passing the channel id as a parameter.
Three messages need to be exchanged between the peers to properly settle the channel, press `Enter` once in the terminal where the settle offer was made, once where the settle offer was received and once more where the settle offer was made for the settlement to be finalized.

To reject the offer, use the `rejectrenewchanneloffer` command, passing the channel id as a parameter.
To reject the offer, use the `rejectrenewchanneloffer` command, passing the channel id as a parameter.
2 changes: 1 addition & 1 deletion sample/examples/configurations/alice.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ networkConfiguration:
peerListeningPort: 9000
network: regtest
oracleConfig:
host: 'https://oracle.p2pderivatives.io/'
host: 'http://localhost:8080/'
2 changes: 1 addition & 1 deletion sample/examples/configurations/bob.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ networkConfiguration:
peerListeningPort: 9001
network: regtest
oracleConfig:
host: 'https://oracle.p2pderivatives.io/'
host: 'http://localhost:8080/'
5 changes: 2 additions & 3 deletions sample/examples/contracts/numerical_contract_input.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"offerCollateral": 100000000,
"acceptCollateral": 100000000,
"maturityTime": 1653378780,
"feeRate": 2,
"contractInfos": [
{
Expand Down Expand Up @@ -76,9 +75,9 @@
},
"oracles": {
"publicKeys": [
"ce4b7ad2b45de01f0897aa716f67b4c2f596e54506431e693f898712fe7e9bf3"
"0d829c1cc556aa59060df5a9543c5357199ace5db9bcd5a8ddd6ee2fc7b6d174"
],
"eventId": "btcusd1653378780",
"eventId": "btcusd1707120297",
"threshold": 1
}
}
Expand Down
13 changes: 7 additions & 6 deletions sample/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ mod hex_utils;
use disk::FilesystemLogger;

use bitcoin::secp256k1::rand::{thread_rng, RngCore};
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use bitcoin::secp256k1::SecretKey;
use bitcoin_rpc_provider::BitcoinCoreProvider;
use dlc_manager::{Oracle, SystemTimeProvider};
use dlc_messages::message_handler::MessageHandler as DlcMessageHandler;
use lightning::ln::peer_handler::{
ErroringMessageHandler, IgnoringMessageHandler, MessageHandler, PeerManager as LdkPeerManager,
};
use lightning::sign::KeysManager;
use lightning::sign::{KeysManager, NodeSigner};
use lightning_net_tokio::SocketDescriptor;
use p2pd_oracle_client::P2PDOracleClient;
use std::collections::hash_map::HashMap;
Expand Down Expand Up @@ -115,10 +115,6 @@ async fn main() {

// Setup a handler for the DLC messages that will be sent/received through LDK.
let dlc_message_handler = Arc::new(DlcMessageHandler::new());
println!(
"Node public key: {}",
PublicKey::from_secret_key(&Secp256k1::new(), &sk)
);

let time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
Expand All @@ -130,6 +126,11 @@ async fn main() {
time.as_nanos() as u32,
));

println!(
"Node public key: {}",
km.get_node_id(lightning::sign::Recipient::Node).unwrap()
);

// The peer manager helps us establish connections and communicate with our peers.
let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
MessageHandler {
Expand Down
12 changes: 12 additions & 0 deletions sample/tests/configurations/alice.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
bitcoinInfo:
rpcUsername: testuser
rpcPassword: lq6zequb-gYTdF2_ZEUtr8ywTXzLYtknzWU4nV8uVoo=
rpcPort: 18443
rpcHost: localhost
wallet: alice
storageDirPath: './dlc_sample_alice'
networkConfiguration:
peerListeningPort: 9000
network: regtest
oracleConfig:
host: 'http://localhost:8080/'
12 changes: 12 additions & 0 deletions sample/tests/configurations/bob.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
bitcoinInfo:
rpcUsername: testuser
rpcPassword: lq6zequb-gYTdF2_ZEUtr8ywTXzLYtknzWU4nV8uVoo=
rpcPort: 18443
rpcHost: localhost
wallet: bob
storageDirPath: './dlc_sample_bob'
networkConfiguration:
peerListeningPort: 9001
network: regtest
oracleConfig:
host: 'http://localhost:8080/'
87 changes: 87 additions & 0 deletions sample/tests/contracts/numerical_contract_input.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
{
"offerCollateral": 100000000,
"acceptCollateral": 100000000,
"feeRate": 2,
"contractInfos": [
{
"contractDescriptor": {
"numerical": {
"payoutFunction": {
"payoutFunctionPieces": [
{
"polynomialPayoutCurvePiece": {
"payoutPoints": [
{
"eventOutcome": 0,
"outcomePayout": 0,
"extraPrecision": 0
},
{
"eventOutcome": 50000,
"outcomePayout": 0,
"extraPrecision": 0
}
]
}
},
{
"polynomialPayoutCurvePiece": {
"payoutPoints": [
{
"eventOutcome": 50000,
"outcomePayout": 0,
"extraPrecision": 0
},
{
"eventOutcome": 60000,
"outcomePayout": 200000000,
"extraPrecision": 0
}
]
}
},
{
"polynomialPayoutCurvePiece": {
"payoutPoints": [
{
"eventOutcome": 60000,
"outcomePayout": 200000000,
"extraPrecision": 0
},
{
"eventOutcome": 1048575,
"outcomePayout": 200000000,
"extraPrecision": 0
}
]
}
}
]
},
"roundingIntervals": {
"intervals": [
{
"beginInterval": 0,
"roundingMod": 1
}
]
},
"differenceParams": null,
"oracleNumericInfos": {
"base": 2,
"nbDigits": [
20
]
}
}
},
"oracles": {
"publicKeys": [
"0d829c1cc556aa59060df5a9543c5357199ace5db9bcd5a8ddd6ee2fc7b6d174"
],
"eventId": "btcusd1707116236",
"threshold": 1
}
}
]
}
75 changes: 75 additions & 0 deletions sample/tests/sample_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use dlc_manager::contract::contract_input::ContractInput;
use rexpect::session::spawn_command;
use std::{
ops::Add,
process::Command,
time::{Duration, UNIX_EPOCH},
};

fn update_contract_offer_time() {
let mut contract_offer: ContractInput = serde_json::from_str(include_str!(
"../tests/contracts/numerical_contract_input.json"
))
.unwrap();
let maturity = std::time::SystemTime::now().add(Duration::from_secs(60 * 3));
let maturity_epoch = maturity.duration_since(UNIX_EPOCH).unwrap().as_secs();
contract_offer.contract_infos[0].oracles.event_id = format!("btcusd{maturity_epoch}");
let updated = serde_json::to_string_pretty(&contract_offer).unwrap();
std::fs::write("./tests/contracts/numerical_contract_input.json", &updated).unwrap();
}

#[test]
#[ignore]
fn sample_offer_accept_test() {
update_contract_offer_time();
bitcoin_test_utils::rpc_helpers::init_clients();
let bin_path = assert_cmd::cargo::cargo_bin("sample");
let mut cmd = Command::new(&bin_path);
cmd.arg("./tests/configurations/alice.yml");

let mut alice_process = spawn_command(cmd, Some(30000)).unwrap();

let (_, alice_node_id) = alice_process.exp_regex("[0-9a-f]{66}").unwrap();

let mut cmd = Command::new(bin_path);
cmd.arg("./tests/configurations/bob.yml");

let mut bob_process = spawn_command(cmd, Some(30000)).unwrap();
bob_process.exp_regex("[0-9a-f]{66}").unwrap();

alice_process.exp_string(">").unwrap();
bob_process.exp_string(">").unwrap();

bob_process
.send_line(&format!("offercontract {alice_node_id}@127.0.0.1:9000 ./tests/contracts/numerical_contract_input.json"))
.unwrap();
bob_process.exp_regex("SUCCESS").unwrap();
bob_process.exp_string(">").unwrap();
alice_process.send_line("").unwrap();
alice_process.exp_string(">").unwrap();
alice_process.send_line("listoffers").unwrap();

let (_, mut contract_id) = alice_process.exp_regex("[0-9a-f]{64}\"").unwrap();
contract_id.pop();

alice_process.exp_string(">").unwrap();
alice_process
.send_line(&format!("acceptoffer {contract_id}"))
.unwrap();
alice_process.exp_string(">").unwrap();

// Give time for accept message to be delivered.
std::thread::sleep(std::time::Duration::from_secs(1));
bob_process.send_line("").unwrap();
bob_process.exp_string("Sending").unwrap();

// Give time for sign message to be delivered.
std::thread::sleep(std::time::Duration::from_secs(1));
alice_process.send_line("").unwrap();
alice_process.exp_string("Processing").unwrap();
alice_process.exp_string(">").unwrap();
alice_process.send_line("listcontracts").unwrap();

// At that point the contract should be in signed state.
alice_process.exp_string("Signed").unwrap();
}

0 comments on commit e30cca5

Please sign in to comment.