区块链研习社

grin 之 Cuckoo Cycle 算法挖矿分析

2019-02-18  本文已影响0人  tpkeeper
Cuckoo Cycle 算法
image.png

8个节点6个边 一个解决方案

grin中挖矿过程

两种算法:Cuck(ar|at)oo cycle (抗asic | 对asic友好) (edg_bits : 29|31+)
solution 环型长度 都是42

  1. hash1=black2b(header+nonce) 其中参与计算的header未包含pow字段
  2. solution,find=cuckoo(hash1)
    cuckoo 把hash1当作SIPHAS0H的种子,然后随机生成M个边,再找出一个环
  3. 如果find,就返回一个solution,然后对该solution 计算hash并对比难度值是否符合要求
    1. 如果符合难度值,则广播区块
    2. 如果不符合难度值,重新组装header+nonce,继续步骤1
  4. 如果没有find,重新组装header+nonce,继续步骤1

code

pub unsafe extern "C" fn run_solver(
    ctx: *mut SolverCtx,
    header_ptr: *const c_uchar,  //不包含pow部分
    header_length: uint32_t,
    nonce: uint64_t,  //随机数
    _range: uint32_t,
    solutions: *mut SolverSolutions, //输出解决方案
    stats: *mut SolverStats,
) -> uint32_t

pub fn new_cuckaroo_ctx<T>(
    edge_bits: u8, // 2^bits 边的图形 2^19
    proof_size: usize, //环形长度 42
) -> Result<Box<dyn PoWContext<T>>, Error>

pub fn set_header_nonce(
    header: &[u8],
    nonce: Option<u64>,
    mutate_nonce: bool,
) -> Result<[u64; 4], Error>

pub fn create_siphash_keys(header: &[u8]) -> Result<[u64; 4], Error>
pub fn search(nodes: &[u32]) -> Result<Vec<Solution>, String>


pub struct CuckooParams<T>
{
    pub edge_bits: u8, //图形边数量 2^bits
    pub proof_size: usize, //环形边数量
    pub num_edges: u64,
    pub siphash_keys: [u64; 4],
    pub edge_mask: T,
}

fn verify(&self, proof: &Proof) -> Result<(), Error> {
        let nonces = &proof.nonces;
        let mut uvs = vec![0u64; 2 * proof.proof_size()];
        let mut xor0: u64 = 0;
        let mut xor1: u64 = 0;
        for n in 0..proof.proof_size() {
            if nonces[n] > to_u64!(self.params.edge_mask) {
                return Err(ErrorKind::Verification("edge too big".to_owned()))?;
            }
            if n > 0 && nonces[n] <= nonces[n - 1] {
                return Err(ErrorKind::Verification("edges not ascending".to_owned()))?;
            }
            let edge = to_edge!(siphash_block(&self.params.siphash_keys, nonces[n]));
            uvs[2 * n] = to_u64!(edge & self.params.edge_mask);
            uvs[2 * n + 1] = to_u64!((edge >> 32) & self.params.edge_mask);
            xor0 ^= uvs[2 * n];
            xor1 ^= uvs[2 * n + 1];
        }
...
...
...
}
参考:
The Mining Loop

All of these systems are put together in the mining loop, which attempts to create
valid Proofs-of-Work to create the latest block in the chain. The following is an outline of what the main mining loop does during a single iteration:

Mining Loop Difficulty Control and Timing

Controlling the overall difficulty of the mining loop requires finding a balance between the three values outlined above:

上一篇 下一篇

猜你喜欢

热点阅读