Skip to content

Commit

Permalink
0.1.0-pre.alpha.3
Browse files Browse the repository at this point in the history
  • Loading branch information
rustyspottedcatt committed Feb 7, 2025
1 parent 8307170 commit edf0803
Show file tree
Hide file tree
Showing 24 changed files with 854 additions and 162 deletions.
6 changes: 2 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
[package]
name = "nebulacrypto"
version = "0.1.0-pre.alpha.2"
version = "0.1.0-pre.alpha.3"
edition = "2024"

[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros", "full"] }
bincode = "1.3"
serde = { version = "1.0", features = ["derive"] }
ed25519-dalek = { version = "2", features = ["rand_core", "serde"]}
ed25519-dalek = { version = "2", features = ["rand_core", "serde"]}
rand = "0.8"
chrono = { version = "0.4.39", features = ["serde"]}
sha2 = "0.10.8"
hex = "0.4.3"
#libp2p = "0.55.0"


[lib]
name = "nebula"
Expand Down
19 changes: 19 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
FROM rust:latest AS builder

WORKDIR /usr/src/nebula

COPY . .

RUN cargo build --release

FROM debian:bullseye-slim AS runtime

RUN apt-get update && apt-get install -y libssl-dev ca-certificates && rm -rf /var/lib/apt/lists/*

WORKDIR /usr/src/nebula

COPY --from=builder /usr/src/nebula/target/release/nebulacrypto /usr/bin/nebula

EXPOSE 8080

ENTRYPOINT ["nebula"]
207 changes: 161 additions & 46 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://l7mozmkiwy.ufs.sh/f/HKemhjN71TyOWR3z3yuKt6z8SiwMQpPjTFX1mVLHuAaolWbN">
<source media="(prefers-color-scheme: dark)" srcset="https://l7mozmkiwy.ufs.sh/f/HKemhjN71TyOwMCPgf4f1Cjl2Pczaro3dH9SEtbyL4AKsVhF">
<img src="https://l7mozmkiwy.ufs.sh/f/HKemhjN71TyOWR3z3yuKt6z8SiwMQpPjTFX1mVLHuAaolWbN" alt="Light Image">
<img src="https://l7mozmkiwy.ufs.sh/f/HKemhjN71TyOWR3z3yuKt6z8SiwMQpPjTFX1mVLHuAaolWbN" alt="Nebula Logo">
</picture>

---

# Nebula (Early Alpha Release v0.1.0-pre.alpha.1)
# Nebula (Early Alpha Release v0.1.0-pre.alpha.3)

![Maintainer](https://img.shields.io/badge/maintainer-rustyspottedcatt-blue)
[![made-with-rust](https://img.shields.io/badge/Made%20with-Rust-1f425f.svg)](https://www.rust-lang.org/)
[![Maintainer](https://img.shields.io/badge/maintainer-rustyspottedcatt-blue)](https://github.com/rustyspottedcatt)
[![Made with Rust](https://img.shields.io/badge/Made%20with-Rust-1f425f.svg)](https://www.rust-lang.org/)
[![License](https://img.shields.io/badge/License-GNU_AGPLv3-blue)](https://choosealicense.com/licenses/agpl-3.0/)

> [!NOTE]
> Nebula is still heavily in work in progress, expect bugs!
>
**Nebula** is a blockchain-based system that replicates ICP's architecture, including neurons, governance, canisters, transactions, and staking. It uses **ed25519-dalek** cryptography for key management, transaction signing, and governance security.
> **NOTE:** Nebula is still under heavy development. Expect bugs and frequent API changes.
Nebula is a blockchain-based system that replicates ICP’s architecture—including neurons, governance, canisters, transactions, and staking. It uses **ed25519-dalek** for key management and transaction signing.

---

Expand All @@ -24,83 +21,192 @@
- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Wallet Management](#wallet-management)
- [Transaction Processing (Direct and via Canisters)](#transaction-processing)
- [Block Production](#block-production)
- [Neuron Management](#neuron-management)
- [Staking](#staking)
- [Governance and Voting](#governance-and-voting)
- [Dependencies](#dependencies)
- [License](#license)

---

## Features

- Wallet Management: Generates private keys, public keys, and blockchain-compatible addresses.
- Transaction Processing: Creates, signs, and submits transactions with dynamic fee and index calculation.
- Consensus Engine: Selects validators, produces blocks, and verifies transactions.
- Governance System: Proposals, voting, and neuron-based decision-making.
- Nervous System: Manages neuron creation, locking/unlocking, and stake delegation.
- Staking Module: Allows users to stake and unstake tokens securely.
- **Wallet Management:** Generate wallets with private keys, public keys, and blockchain-compatible addresses.
- **Transaction Processing:** Build, sign, and submit transactions with dynamic fee and index calculation.
- **Consensus Engine:** Validator selection, block production, and transaction verification.
- **Governance:** Neuron-based proposals and voting.
- **Nervous System:** Neuron creation, locking/unlocking, and stake delegation.
- **Staking:** Secure staking and unstaking of tokens.
- **Canisters:** Wrap functionality (e.g., transaction submission, staking) into canisters for modularity and secure isolation.

---

## Installation

### Prerequisites

Ensure you have the following installed:
- Rust (latest stable version)
- Rust Nightly
- Rust (latest stable)
- Cargo package manager

### Clone the Repository

```sh
$ git clone https://github.com/rustyspottedcatt/nebula
$ cd nebula
git clone https://github.com/rustyspottedcatt/nebula.git
cd nebula
```

### Build the Project

```sh
$ cargo build --release
cargo build --release
```

### Run the Application

```sh
$ cargo run
cargo run
```

---

## Usage

### Creating a Wallet
### Wallet Management

Create a wallet using the built-in function. The wallet returns a private key, a public key (as a VerifyingKey), and an address.

```rust
use core::api::v1::*;
use crate::core::api::v1::wallet::create_wallet;

let (signing_key, _public_key, address) = create_wallet();
println!("Wallet created: {:x?}", address); // Shareable (used to exchange)
println!("Public Key: {}", public_key); // Shareable
println!("Private Key: {}", signing_key); // Do not SHARE
let (signing_key, public_key, address) = create_wallet();
println!("Wallet created: {:x?}", address); // Shareable address
println!("Public Key: {:?}", public_key); // Safe to share
println!("Private Key: {:?}", signing_key); // DO NOT SHARE!
```

### Creating and Signing Transactions
### Transaction Processing

#### Direct Transaction Creation

The following example shows how to build, sign, and submit a transaction directly using the consensus engine (without a canister).

```rust
use core::api::v1::*;
use crate::core::api::v1::transaction::{build_transaction, finalize_transaction, submit_transaction};
use crate::core::types::TransactionType;

// Assume consensus_engine is already initialized and sender/receiver ledger accounts exist.
let amount = 50;
let mut tx = build_transaction(
&mut consensus_engine,
sender_address, // sender's address
receiver_address, // receiver's address
amount,
0, // memo
0, // nrc_memo
TransactionType::Transfer
);
finalize_transaction(&mut tx, &signing_key)?; // Signs the transaction
submit_transaction(&mut consensus_engine, tx)?; // Submits to the mempool
```

#### Transaction Submission via Canisters

let recipient = "recipient_address".to_string();
let amount = 100;
Nebula allows you to wrap functionality in a canister. In the example below, we create a canister, initialize ledger accounts for sender and receiver, build and sign a transaction, then submit it via the canister.

let mut tx = build_transaction(&mut consensus_engine, address, recipient, amount);
finalize_transaction(&mut tx)?;
submit_transaction(&mut consensus_engine, tx)?;
```rust
use crate::core::api::v1::transaction::{submit_transaction, build_transaction, finalize_transaction};
use crate::core::api::v1::wallet::create_wallet;
use crate::core::canister::canister::{Canister, CanisterFunctionPayload};
use crate::core::canister::registry::CanisterRegistry;
use crate::core::consensus::{ValidatorInfo};
use crate::core::consensus::model::ConsensusEngine;
use crate::core::nervous::NervousSystem;
use crate::core::types::TransactionType;

#[tokio::main]
async fn main() {
// Create wallet for sender.
let (signing_key, public_key, address) = create_wallet();
println!("Wallet created: {:x?}", address);

// Create and register a canister.
let mut canister_registry = CanisterRegistry::new();
let canister_id = "my_canister".to_string();
let canister = Canister::new(canister_id.clone(), address.clone());
println!("Canister ID: {}", canister.canister_id);
canister_registry.register_canister(&canister_id, canister);
let mut registered_canister = match canister_registry.get_canister(&canister_id) {
Some(c) => c,
None => {
eprintln!("Canister '{}' not found", canister_id);
return;
}
};

// Use canister-based API to submit a transaction.
{
// Create a wallet for the receiver.
let (_signing_key1, public_key1, address1) = create_wallet();

// Initialize the Nervous System and Consensus Engine.
let nervous_system = NervousSystem::new();
let validators = vec![ValidatorInfo { address: address.clone(), active: true }];
let mut consensus_engine = ConsensusEngine::new(validators, nervous_system.neurons.clone());

// Initialize ledger accounts for sender and receiver.
consensus_engine.init_ledger(address.clone(), public_key, 100)
.expect("Failed to initialize sender ledger");
consensus_engine.init_ledger(address1.clone(), public_key1, 0)
.expect("Failed to initialize receiver ledger");

let amount = 50;
// Build and sign the transaction.
let mut tx = build_transaction(
&mut consensus_engine,
address.clone(),
address1.clone(),
amount,
0,
0,
TransactionType::Transfer
);
finalize_transaction(&mut tx, &signing_key)
.expect("Failed to sign the transaction");

// Create a transfer payload for the canister.
let transfer_payload = CanisterFunctionPayload::Transfer {
consensus_engine: &mut consensus_engine,
tx,
};

// Execute the transaction via the canister.
match registered_canister.execute_function(transfer_payload) {
Ok(msg) => println!("Successfully sent transfer: {}", msg),
Err(err) => eprintln!("Transfer failed: {}", err),
}
}
}
```

### Producing a Block
### Block Production

After transactions are in the mempool, you can produce a block:

```rust
use crate::core::consensus::block::produce_block;

let block = produce_block(&mut consensus_engine, &signing_key)?;
println!("Block produced with {} transaction(s)", block.transactions.len());
println!("Block produced with {} transactions", block.transactions.len());
println!("Block timestamp: {}", block.header.timestamp);
```

### Neuron Management

Create a neuron for governance:

```rust
use crate::core::nervous::neuron_handler::create_neuron;

Expand All @@ -109,26 +215,32 @@ println!("Neuron created with id: {}", neuron_id);
```

### Staking

Stake tokens to a neuron:

```rust
use crate::core::staking::staking_handler::{stake, unstake};

// init consensus_engine beforehand
let mut staking_module = core::staking::staking_module::StakingModule::new(nervous_system.neurons.clone());
stake(&mut staking_module, &signing_key, neuron_id, 50)?;
stake(&mut staking_module, &mut consensus_engine, &signing_key, neuron_id, 50)?;
println!("Staked 50 tokens to neuron {}", neuron_id);
```

### Governance and Voting

Submit a proposal and vote:

```rust
use crate::core::governance::{proposal_handler::propose, voting::{vote, finalize}};

let governance = core::governance::Governance::new(nervous_system.neurons.clone());

let proposal_id = propose(&governance, "Increase block size".to_string(), &signing_key, neuron_id)?;
println!("Proposal created with id: {}", proposal_id);

match vote(&governance, &signing_key, neuron_id, proposal_id, true, 10) {
Ok(_) => println!("Voted on proposal {}", proposal_id),
Err(e) => println!("Voting failed: {}", e),
Ok(_) => println!("Voted on proposal {}", proposal_id),
Err(e) => println!("Voting failed: {}", e),
}

let proposal_result = finalize(&governance, proposal_id)?;
Expand All @@ -139,19 +251,22 @@ println!("Proposal finalized with result: {}", proposal_result);

## Dependencies

Add the following to your `Cargo.toml`:

```toml
[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros", "full"] }
bincode = "1.3"
serde = { version = "1.0", features = ["derive"] }
ed25519-dalek = { version = "2", features = ["rand_core", "serde"] }
rand = "0.8"
chrono = { version = "0.4.39", features = ["serde"] }
sha2 = "0.10.8"
hex = "0.4.3"
chrono = { version = "0.4", features = ["serde"] }
sha2 = "0.10"
hex = "0.4"
```

---

## License

Distributed under the [GNU AGPLv3](https://choosealicense.com/licenses/agpl-3.0/) license.
Distributed under the [GNU AGPLv3](https://choosealicense.com/licenses/agpl-3.0/) license.
1 change: 1 addition & 0 deletions src/core/api/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod v1;
11 changes: 0 additions & 11 deletions src/core/api/v1/blockchain.rs

This file was deleted.

23 changes: 23 additions & 0 deletions src/core/api/v1/consensus.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use ed25519_dalek::SigningKey;
use crate::core::canister::canister::{Canister, CanisterFunctionPayload};
use crate::core::consensus::model::ConsensusEngine;

pub fn produce_block(
canister: &mut Canister,
consensus_engine: &mut ConsensusEngine,
signing_key: &SigningKey,
) -> Result<String, String> {
canister.execute_function(CanisterFunctionPayload::ProduceBlock {
consensus_engine,
signing_key,
})
}

pub fn select_next_validator(
canister: &mut Canister,
consensus_engine: &mut ConsensusEngine,
) -> Result<String, String> {
canister.execute_function(CanisterFunctionPayload::SelectValidator {
consensus_engine,
})
}
Loading

0 comments on commit edf0803

Please sign in to comment.