Skip to content

Feat:Add example project ed25519 #350

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,637 changes: 3,637 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions basics/ed25519_example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.anchor
.DS_Store
target
**/*.rs.bk
node_modules
test-ledger
.yarn
7 changes: 7 additions & 0 deletions basics/ed25519_example/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.anchor
.DS_Store
target
node_modules
dist
build
test-ledger
18 changes: 18 additions & 0 deletions basics/ed25519_example/Anchor.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[toolchain]

[features]
resolution = true
skip-lint = false

[programs.localnet]
ed_25519_example = "5qymHa7CTb6mQkhmKpTv5rstKc4TyYcJ7hkBSi2mPnkH"

[registry]
url = "https://api.apr.dev"

[provider]
cluster = "Localnet"
wallet = "~/.config/solana/id.json"

[scripts]
test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
14 changes: 14 additions & 0 deletions basics/ed25519_example/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[workspace]
members = [
"programs/*"
]
resolver = "2"

[profile.release]
overflow-checks = true
lto = "fat"
codegen-units = 1
[profile.release.build-override]
opt-level = 3
incremental = false
codegen-units = 1
12 changes: 12 additions & 0 deletions basics/ed25519_example/migrations/deploy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.

const anchor = require("@coral-xyz/anchor");

module.exports = async function (provider) {
// Configure client to use the provider.
anchor.setProvider(provider);

// Add your deploy script here.
};
22 changes: 22 additions & 0 deletions basics/ed25519_example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"license": "ISC",
"scripts": {
"lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
"lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
},
"dependencies": {
"@coral-xyz/anchor": "^0.30.1",
"@noble/ed25519": "^2.2.3",
"tweetnacl": "^1.0.3"
},
"devDependencies": {
"@types/bn.js": "^5.1.0",
"@types/chai": "^4.3.0",
"@types/mocha": "^9.0.0",
"chai": "^4.3.4",
"mocha": "^9.0.3",
"prettier": "^2.6.2",
"ts-mocha": "^10.0.0",
"typescript": "^4.3.5"
}
}
20 changes: 20 additions & 0 deletions basics/ed25519_example/programs/ed_25519_example/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "ed_25519_example"
version = "0.1.0"
description = "Created with Anchor"
edition = "2021"

[lib]
crate-type = ["cdylib", "lib"]
name = "ed_25519_example"

[features]
default = []
cpi = ["no-entrypoint"]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
idl-build = ["anchor-lang/idl-build"]

[dependencies]
anchor-lang = "0.30.1"
2 changes: 2 additions & 0 deletions basics/ed25519_example/programs/ed_25519_example/Xargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[target.bpfel-unknown-unknown.dependencies.std]
features = []
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use anchor_lang::error_code;

#[error_code]
pub enum ProgramErrorCode {
#[msg("Invalid ed25519 instruction")]
Invalid25519Instruction,
#[msg("Invalid admin signature")]
InvalidAdminSignature,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use anchor_lang::prelude::*;
use anchor_lang::solana_program::instruction::Instruction;
use anchor_lang::solana_program::{
sysvar::instructions::{load_instruction_at_checked, ID as IX_ID},
};
use crate::errors::ProgramErrorCode;

use crate::utils::ed25519::verify_ed25519_ix;

#[derive(Accounts)]
pub struct Ed25519Example<'info> {
/// The signer of the message
#[account(mut)]
pub signer: Signer<'info>,

/// Instruction sysvar account needed for ed25519 verification
/// CHECK: This is the instructions sysvar
#[account(address = IX_ID)]
pub ix_sysvar: AccountInfo<'info>,
}

impl<'info> Ed25519Example<'info> {
pub fn verify_signature(
&self,
message: [u8; 64],
admin_pubkey_bytes: [u8; 32],
signature: [u8; 64],
) -> Result<()> {
// Get the Ed25519Program instruction which should be first (index 0)
let ix: Instruction = anchor_lang::solana_program::sysvar::instructions::load_instruction_at_checked(
0,
&self.ix_sysvar
)?;

// Verify the signature
verify_ed25519_ix(&ix, &admin_pubkey_bytes, &message, &signature)?;

Ok(())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub use ed25519_example::*;
pub mod ed25519_example;
22 changes: 22 additions & 0 deletions basics/ed25519_example/programs/ed_25519_example/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use anchor_lang::prelude::*;

declare_id!("5qymHa7CTb6mQkhmKpTv5rstKc4TyYcJ7hkBSi2mPnkH");
use instructions::*;
pub mod instructions;
pub mod utils;
pub mod errors;


#[program]
pub mod ed_25519_example {
use super::*;

pub fn verify_message(
ctx: Context<Ed25519Example>,
message: [u8; 64],
admin_pubkey_bytes: [u8; 32],
signature: [u8; 64],
) -> Result<()> {
ctx.accounts.verify_signature(message, admin_pubkey_bytes, signature)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use anchor_lang::prelude::*;
use anchor_lang::solana_program::instruction::Instruction;
use anchor_lang::solana_program::ed25519_program::ID as ED25519_ID;
use crate::errors::ProgramErrorCode;

use std::convert::TryInto;

/// Verify Ed25519Program instruction fields
pub fn verify_ed25519_ix(ix: &Instruction, pubkey: &[u8], msg: &[u8], sig: &[u8]) -> Result<()> {
if ix.program_id != ED25519_ID || // The program id we expect
ix.accounts.len() != 0 || // With no context accounts
ix.data.len() != (16 + 64 + 32 + msg.len()) // And data of this size
{
return Err(ProgramErrorCode::Invalid25519Instruction.into()); // Otherwise, we can already throw err
}

check_ed25519_data(&ix.data, pubkey, msg, sig)?; // If that's not the case, check data

Ok(())
}

/// Verify serialized Ed25519Program instruction data
pub fn check_ed25519_data(data: &[u8], pubkey: &[u8], msg: &[u8], sig: &[u8]) -> Result<()> {
// According to this layout used by the Ed25519Program
// https://github.com/solana-labs/solana-web3.js/blob/master/src/ed25519-program.ts#L33

// "Deserializing" byte slices

let num_signatures = &[data[0]]; // Byte 0
let padding = &[data[1]]; // Byte 1
let signature_offset = &data[2..=3]; // Bytes 2,3
let signature_instruction_index = &data[4..=5]; // Bytes 4,5
let public_key_offset = &data[6..=7]; // Bytes 6,7
let public_key_instruction_index = &data[8..=9]; // Bytes 8,9
let message_data_offset = &data[10..=11]; // Bytes 10,11
let message_data_size = &data[12..=13]; // Bytes 12,13
let message_instruction_index = &data[14..=15]; // Bytes 14,15

let data_pubkey = &data[16..16+32]; // Bytes 16..16+32
let data_sig = &data[48..48+64]; // Bytes 48..48+64
let data_msg = &data[112..]; // Bytes 112..end

// Expected values

let exp_public_key_offset: u16 = 16; // 2*u8 + 7*u16
let exp_signature_offset: u16 = exp_public_key_offset + pubkey.len() as u16;
let exp_message_data_offset: u16 = exp_signature_offset + sig.len() as u16;
let exp_num_signatures: u8 = 1;
let exp_message_data_size: u16 = msg.len().try_into().unwrap();

// Header and Arg Checks

// Header
if num_signatures != &exp_num_signatures.to_le_bytes() ||
padding != &[0] ||
signature_offset != &exp_signature_offset.to_le_bytes() ||
signature_instruction_index != &u16::MAX.to_le_bytes() ||
public_key_offset != &exp_public_key_offset.to_le_bytes() ||
public_key_instruction_index != &u16::MAX.to_le_bytes() ||
message_data_offset != &exp_message_data_offset.to_le_bytes() ||
message_data_size != &exp_message_data_size.to_le_bytes() ||
message_instruction_index != &u16::MAX.to_le_bytes()
{
return Err(ProgramErrorCode::InvalidAdminSignature.into());
}

// Arguments
if data_pubkey != pubkey ||
data_msg != msg ||
data_sig != sig
{
return Err(ProgramErrorCode::InvalidAdminSignature.into());
}

Ok(())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub use ed25519::*;

pub mod ed25519;
60 changes: 60 additions & 0 deletions basics/ed25519_example/tests/ed_25519_example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Ed25519Example } from "../target/types/ed25519_example";
import * as ed from "@noble/ed25519";
import { sha512 } from "@noble/hashes/sha512";
import { sha256 } from "@noble/hashes/sha256";
import { randomBytes } from 'tweetnacl';

ed.etc.sha512Sync = (...m) => sha512(ed.etc.concatBytes(...m));


describe("ed25519_example", () => {
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);

const program = anchor.workspace.Ed25519Example as Program<Ed25519Example>;
const payer = anchor.Wallet.local().payer;

const admin = anchor.web3.Keypair.generate();
let msg = new Uint8Array(64);
msg.set(sha256(randomBytes(64)));

it("Check signature!", async () => {
// Add your test here.
const edSignature = ed.sign(msg, admin.secretKey.slice(0, 32));

const instruction = await program.methods
.verifyMessage(Array.from(msg), Array.from(admin.publicKey.toBytes()), Array.from(edSignature))
.accounts({
signer: payer.publicKey,
})
.instruction();

let tx = new anchor.web3.Transaction()
.add(
// Ed25519 instruction
anchor.web3.Ed25519Program.createInstructionWithPublicKey({
publicKey: admin.publicKey.toBytes(),
message: msg,
signature: edSignature,
})
)
.add(instruction);
const { lastValidBlockHeight, blockhash } = await provider.connection.getLatestBlockhash();
tx.lastValidBlockHeight = lastValidBlockHeight;
tx.recentBlockhash = blockhash;
tx.feePayer = payer.publicKey;

tx.sign(payer, payer);

const signature = await provider.connection.sendRawTransaction(tx.serialize());

await provider.connection.confirmTransaction({
signature,
blockhash,
lastValidBlockHeight,
});
console.log("Your transaction signature", tx);
});
});
10 changes: 10 additions & 0 deletions basics/ed25519_example/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"types": ["mocha", "chai"],
"typeRoots": ["./node_modules/@types"],
"lib": ["es2015"],
"module": "commonjs",
"target": "es6",
"esModuleInterop": true
}
}
46 changes: 46 additions & 0 deletions basics/ed25519_example/yarn-error.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
Arguments:
/Users/dogukangundogan/.nvm/versions/node/v22.12.0/bin/node /usr/local/bin/yarn install

PATH:
/Users/dogukangundogan/.nvm/versions/node/v22.12.0/bin:/Users/dogukangundogan/.fuelup/bin:/Users/dogukangundogan/.detaspace/bin:/opt/homebrew/opt/gnu-tar/libexec/gnubin:/Users/dogukangundogan/Documents/flutter/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/Users/dogukangundogan/.local/share/solana/install/active_release/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/Library/Apple/usr/bin:/usr/local/share/dotnet:~/.dotnet/tools:/usr/local/go/bin:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Users/dogukangundogan/.nvm/versions/node/v22.12.0/bin:/Users/dogukangundogan/.fuelup/bin:/Users/dogukangundogan/.detaspace/bin:/opt/homebrew/opt/gnu-tar/libexec/gnubin:/Users/dogukangundogan/Documents/flutter/bin:/opt/anaconda3/bin:/opt/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/Users/dogukangundogan/.local/share/solana/install/active_release/bin:/Users/dogukangundogan/.cargo/bin:/Users/dogukangundogan/.foundry/bin:/Users/dogukangundogan/.local/bin:/Users/dogukangundogan/.pub-cache/bin:/usr/local/bin:/Users/dogukangundogan/.local/bin:/Users/dogukangundogan/.pub-cache/bin:/Users/dogukangundogan/.local/bin

Yarn version:
1.22.19

Node version:
22.12.0

Platform:
darwin arm64

Trace:
Error: getaddrinfo ENOTFOUND registry.yarnpkg.com
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:120:26)

npm manifest:
{
"license": "ISC",
"scripts": {
"lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
"lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
},
"dependencies": {
"@coral-xyz/anchor": "^0.30.1"
},
"devDependencies": {
"chai": "^4.3.4",
"mocha": "^9.0.3",
"ts-mocha": "^10.0.0",
"@types/bn.js": "^5.1.0",
"@types/chai": "^4.3.0",
"@types/mocha": "^9.0.0",
"typescript": "^4.3.5",
"prettier": "^2.6.2"
}
}

yarn manifest:
No manifest

Lockfile:
No lockfile
3 changes: 3 additions & 0 deletions settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"rust-analyzer.check.command": "check"
}