[关闭]
@zhongdao 2017-12-21T08:00:55.000000Z 字数 84484 阅读 7009

part2: 区块链设计与实现笔记v2

未分类


拟定目录大纲:
Part1: 比特币与区块链
1. 比特币技术原理
2. 比特币协议
3. 硬分叉
4. 侧链设计原理
5. 侧链开发
6. 智能合约设计原理
7. 智能合约开发
8. 区块链生态介绍
9. 区块链应用

Part2: 设计与实现笔记
1. 区块链原理机制与背景
2. 区块链基本结构
3. 加解密算法实现
4. 区块数据结构从定义到初步实现
5. 区块节点读取验证与挖矿
6. 节点和应用程序之间协议
7. 节点之间沟通

Part3: 区块链相关基础知识
1. 计算机基础知识
1. Linux相关说明
3. 密码学相关说明
4. 程序开发语言相关说明
5. 虚拟机语言

第三期课程:
区块链设计与实现笔记v1: https://www.zybuluo.com/zhongdao/note/933849

Part1: 比特币与区块链v2
Part2: 区块链设计与实现笔记v2 https://www.zybuluo.com/zhongdao/note/992471
Part3: 区块链相关基础知识v2

若有更正请联系: 李君
邮件: junlicn@foxmail.com
2017.12.20

实际自动导航目录:

0.前言

0.1 内容来源

区块链技术开发公开课:
授课老师: 辕询, 李涛涛
直播地址: http://itgege.gensee.com/webcast/site/entry/join-b0836bdd98c24eb78c67d3a0993b1589

0.2 笔记v1缘起

根据老师公开课上讲的内容, 构造一个完整笔记,便于学习和掌握. 随着课程的进展, 不断添加和整理.
此文档的完整内容来自:公开的课程内容、源代码,资料、搜索引擎搜到的资料、相关技术书籍上的资料等, 我对内容做了整理,使得易于阅读和条理化,对于部分代码添加了注释和自己的理解, 若有错误请沟通纠正。
其中引用到一些同学的笔记内容或者截图,其他笔记内容来源者包括: 程书芝, 袁丁逸涵, 郜晶, liuhongshuo, 谭东雷, 潘杰 ...
笔记编写过程中有张博成,pz100等对错误之处给出了的修订建议.
要特别感谢老师依据开源传统所教授的内容.

0.3 笔记v2缘起

区块链技术开发公开课开始了第四期,然而三期因为时间精力等因素记得不全,再加上因为编辑内容太多,需要分开成几部分,重新进行规划。
Part1 收集整理比特币的相关技术与知识,入门,背景以及深入的技术介绍。
Part2 以课程老师的讲解和实现为主记录的笔记。
Part3 以区块链实现过程当中所需的基础知识为主,涵盖老师所讲的语言,系统,编译原理,密码学等基础知识,也包括从互联网,书本上的相关知识分类整理。

0.4 内容编写原则与目的

从理论到程序实现,清晰明了,易于理解,从比特币,区块链的基础知识介绍到依循老师所讲的内容自己创建一个区块链,同时补充所需的计算机基础知识,从密码学,算法,Linux系统操作, 程序开发语言到虚拟机语言等。

0.5 每次课程摘要

  1. 主要内容:
  2. 1. 区块链的基本结构;
  3. 2. 为什么私钥最重要,以及随机数 –> 私钥 -> 公钥 -> 地址的生成过程;
  4. 3. 文件系统的结构;
  5. 4. 每个区块链程序都由三种基本协议组成
  6. a) A协议:节点内部的规则,数据格式、交易规则、加密/解密算法等;
  7. b) B协议:应用程序与节点沟通的协议;
  8. c) C协议:节点之间沟通的协议;
  9. 5. 区块间隔和冲突处理机制;
  10. 6. 计算机的数据存储及区块链数据结构。

1. 区块链原理与背景

1.0 设计理念

During system design, the major data structure for the software are identified; without these, the system modules cannot be mean
software cannot be meaningfully repaired only rewritten.

从2008年末中本聪的白皮书发出到2009年初中本聪的程序完成,有4个月时间。
开始设计好了,后期的维护成本会很小。
一如Unix的设计理念。
亦来云没有文件和文件夹的概念, 只有服务。

出于教学的目的,为了便于理解,CCN设计得非常简洁,保留了核心的部分,去掉了不必要的部分。

2.区块链基本结构

2.1 区块图示

结构示意:
此处输入图片的描述

或者如下图示意:
image_1btodhc8onfa1mdp10u21pa11ckqm.png-83.1kB
Merkle root 存的hash是为了确保身部所有的交易无法被修改.
Previous Hash是对前一个区块的头header的hash.

4个连续区块及相应交易的例子展示
image_1buj18dmu14ub7v4d511avk1aaim.png-35.9kB
image_1buj1ebcppjaj9j10451b32hv513.png-35.6kB

2.2 区块定义

ConciseCoin(CCN)是一个数码货币系统。

BLOCK := HEAD, TRANSACTION*
HEAD := current(32), nonce(4), previous(32), target(32), time(4), valence(4)
TRANSACTION := A, B, C, INPUT*, OUTPUT*
INPUT := A, index(4), B, public(B), C, signature(C), transaction(32)
OUTPUT := A, B, address(B), amount(8)

  1. HEAD - 5 attribute 108BYTE
  2. BODY - 1 or more TRANSACTION
  3. TRANSACTION - 1 or more INPUT and OUTPUT
  4. COINBASE (创始, 挖矿奖励)
  1. HEAD
  2. CURRENT: 32
  3. NONCE: 4
  4. PREVIOUS: 32 -> completely zero if genesis block
  5. TARGET: 32
  6. TIME: 4
  7. BODY
  8. TRANSACTION #1
  9. INPUTS: 1
  10. INDEX: 4 -> completely zero
  11. PUBLIC: 0
  12. SIGNATURE: 0
  13. TRANSACTION: 32 -> completely zero
  14. OUTPUTS: 1
  15. ADDRESS: 灵活 -> miner's address
  16. AMOUNT: 8 -> 50 或者 100 (挖矿奖励)
  17. TRANSACTION #2
  18. TRANSACTION #3
  19. INPUTS: 1个或者多个
  20. INDEX: 4
  21. PUBLIC: 灵活
  22. SIGNATURE: 灵活
  23. TRANSACTION: 32
  24. OUTPUTS: 1个或者多个
  25. ADDRESS: 灵活
  26. AMOUNT: 8

2.3 密码学算法实现步骤简要说明

随机数字 -> 私钥 -> 公钥 -> 地址

加密和解密最大的危险就是是否产生真正的随机数.

  1. a = open ("/dev/arandom") 打开文件
  2. b = read (a 128) 随机数包括[0 - 256)
  3. c = get.private (b) 私钥
  4. d = get.public (c) 公钥
  5. e = get.address (d) 地址

2.4 交易过程说明

2.4.1 交易过程图示

image_1btoaked7g6m15uo19okr2tsirm.png-233.9kB
每一个人随时控制N个地址,每一个地址随时包含N个碎片。

2.4.2 区块中第1个交易用于矿工

  1. 1个交易是矿工奖励, Transaction中的output要设为矿工的地址, 这里的实现用公钥代替.
  2. 所以构建时,要取得矿工的地址.

3. 密码学算法实现

3.1. 密码学相关说明

密码学在区块链的应用:hash函数 椭圆曲线数字签名

image_1btobo6mh1cpr16ui1lvo3erlvj1g.png-39kB

3.1.1 hash的应用

1.Tx的hash和Merkle root
2.地址生成 —>节约空间
3.挖矿 hash(x||N)难于解决易于验证
4.连接

image_1btobljiu1bq0i1t1q3c1g5l12tn13.png-155.3kB

3.1.2 椭圆曲线

Elliptal Cirue Digital Signature Algorthim
ECC: Elliptal Curve Crypeogaphy. 加解密
ECDSA: 签名和验证的.

超级计算机速度: 4万亿/s
找到碰撞 需要计算 4万亿年.

3.1.3 安全库说明

不是操作系统或者标准化的函数库叫做第三方库.
libtomcrypt是个第三方库.
1. Libtomcrypt
2. OpenSSL

3.2 加解密算法实现代码说明

3.2.1 md5

md5 输出 128bit, 每8bit为1个字节, 也就是16个字节, 1个字节2^8 [0,256)用2个字母表示(00-ff), 共计32个字母
换成sha256时, 需要把16字节out数组改为32字节out

  1. // MD5输出128bit SHA1输出160bit SHA256输出256bit .
  2. // c语言里 %x表示16进制, 会输出2个字母.
  3. // SHA256 输出 256bit, 32个字节, 64个字符.
  4. #include "tomcrypt.h"
  5. int main(int count, char **arguments)
  6. {
  7. hash_state md;
  8. unsigned char *in = "lijun", out[16];
  9. /* setup the hash */
  10. md5_init(&md);
  11. /* add the message */
  12. md5_process(&md, in, strlen(in));
  13. /* get the hash in out[0..15] */
  14. md5_done(&md, out);
  15. for(int i = 0; i < 16; i++)
  16. {
  17. printf("%02x", out[i]); // %02x 表示输出2个字符的16进制,否则0时会省略掉.
  18. }
  19. printf("\n");
  20. return 0;
  21. }
  22. }

3.2.2 sha256

  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #include "string.h"
  4. #include "tomcrypt.h" //密码库
  5. char *get_file(char *path){ //读取文件
  6. FILE *file;
  7. int length;
  8. char *contents;
  9. //获取文件长度
  10. file = fopen(path , "r+");
  11. fseek(file , 0 , SEEK_END); //跳到文件结尾
  12. length = ftell(file); //给出文件长度
  13. fseek(file , 0 ,SEEK_SET); //再跳回文件开头
  14. //分配内存,读取文件
  15. //! 最初的代码是length+1, 改为length
  16. contents = malloc(length); //给文件分配内存
  17. fread(contents , 1 , length , file);
  18. //关闭文件, 系统同时打开的文件个数是有限的,约4900+
  19. fclose(file);
  20. return contents ; //返回文件内容
  21. }
  22. void main(){ //对文本进行Hash加密
  23. char *input , *output;
  24. int length;
  25. output = malloc(1000); //分配1000字节的内存
  26. length = 1000;
  27. input = get_file("essay.txt"); //读取文件
  28. register_hash(&sha256_desc); //激活哈希函数,必须!!
  29. hash_memory(find_hash("sha256") , input , strlen(input) , output , &leng)
  30. printf("%s" , output);
  31. //printf("%d%c" , length , 10); //打印长度
  32. //printf("%02x%c" , output[0] , 10); //打印第一个字符,%02x:十六进制
  33. }

3.2.3 获取私钥

  1. unsigned char *get_private(unsigned int *length)
  2. {
  3. prng_state random; // 随机生产器的状态.
  4. ecc_key key; //保存私钥和公钥的数据结构
  5. unsigned char *buffer;
  6. buffer = malloc(*length = 1000);
  7. // 随机生成器状态, 系统随机生成器, ?, 保存位置
  8. ecc_make_key(&random, find_prng("sprng"), 32, &key); //创建一个私钥
  9. // 把其私钥转换成可打印的字符串.
  10. ecc_export(buffer, length, PK_PRIVATE, &key);
  11. return buffer;
  12. }

3.2.4 获取公钥

  1. unsigned char *get_public(unsigned int *length, unsigned char *private)
  2. {
  3. ecc_key key;
  4. unsigned char *buffer;
  5. //导入私钥
  6. ecc_import(private, *length, &key);
  7. buffer = malloc(*length = 1000);
  8. // 输出公钥
  9. ecc_export(buffer, length, PK_PUBLIC, &key);
  10. return buffer;
  11. }

3.2.5 编码输出

Extra libraries: TomsFastMath library
每次使用tomcryp函数库时, 必须要有如下一行,这是它的固定规则:
ltc_mp = tfm_desc;

将private, public输出的生字节, 用base64转换成ASCII. 便于和其他人共享.

  1. void main()
  2. {
  3. unsigned char *private, *public, *buffer;
  4. unsigned int length_private, length_public, length_buffer;
  5. ltc_mp = tfm_desc;
  6. register_prng(&sprng_desc); //激活函数
  7. register_hash(&sha256_desc);
  8. private = get_private(&length_private);
  9. length_public = length_private;
  10. public = get_public(&length_public, private);
  11. buffer = malloc(1000);
  12. // tomcrypt库函数_ecc_xxx 生产出自己的私钥, 生成的是生字节.
  13. memset(buffer, 0, 1000);
  14. base64_encode(private, length_private, buffer, &length_buffer);
  15. printf("%s%c%c", buffer, 10, 10);
  16. memset(buffer, 0, 1000);
  17. base64_encode(public, length_public, buffer, &length_buffer);
  18. printf("%s%c", buffer, 10);
  19. }

4. 区块数据结构从定义到初步实现

4.1 整体结构定义与区块交易示例

4.1.1 各部分具体定义

BLOCK:

字段名: HEAD BODY(TRANSACTIONS*)
说明: 头部 身部(多个交易)

HEAD:

字段说明 current nounce previous target time valence
说明 BODY的sha256输出 挖矿难度 前个区块的ID 越大难度越小 ?时间 交易个数
长度(字节) 32 4 32 32 4 4

总长:108 (BTC为80)

Transaction

字段名 A B C Input* Output*
说明 总长度(含自己) 输入个数 输出个数 输入列表 输出列表
长度(字节) 4 4 4 B C

实例:
input: #1. 30, #2 40, #3 50
output: #1 100, #2 19 (隐含的手续费=sum(input)-sum(output) )
数据结构表示:
Head, coinbase, A, 3, 2, input#1, input#2, input#3, output#1,output#2
coinbase是第一个交易.

构造区块的顺序:
第2个及之后交易, coinbase, 最后造头
因为要计算手续费, 还有由所有交易构造merkle tree root

INPUT:

字段名 A (碎片号) index B public C Signature Transaction的sha256
说明 总长(交易中的第几个碎片) 第几个Input public长度 公钥 签名长度 签名 交易的hash, merkle root
长度(字节) 4 4 4(33 or 65) B 4 C(<=73,不固定) 32

OUTPUT:

字段名 A B Address Amount
说明 总长度 地址长度 交易地址 交易数量
长度(字节) 4 4 B 8

4.1.2 区块交易实例

  1. #1: 3930
  2. [8629] -> YUANXUN(100)
  3. #2: 4479
  4. [4140] -> YUANXUN(100)
  5. [7159] YUANXUN/8629/1 -> YUANXUN(99) PANPENG(1)
  6. A index B public C signature transaction

4.3.2 头部和身部的另一种定义

整体

  1. HEAD - 6 attribute 108BYTE
  2. BODY - 1 or more TRANSACTION
  3. TRANSACTION - 1 or more INPUT and OUTPUT
  4. COINBASE (创始, 挖矿奖励)

头部和身部具体

  1. HEAD
  2. CURRENT: 32
  3. NONCE: 4
  4. PREVIOUS: 32 -> completely zero if genesis block
  5. TARGET: 32
  6. TIME: 4
  7. VALENCE: 4
  8. BODY
  9. TRANSACTION #1
  10. INPUTS: 1
  11. INDEX: 4 -> completely zero
  12. PUBLIC: 0
  13. SIGNATURE: 0
  14. TRANSACTION: 32 -> completely zero
  15. OUTPUTS: 1
  16. ADDRESS: 灵活 -> miner's address
  17. AMOUNT: 8 -> 50 huozhe 100
  18. TRANSACTION #2
  19. TRANSACTION #3
  20. INPUTS: 1个或者多个
  21. INDEX: 4
  22. PUBLIC: 灵活
  23. SIGNATURE: 灵活
  24. TRANSACTION: 32
  25. OUTPUTS: 1个或者多个
  26. ADDRESS: 灵活
  27. AMOUNT: 8

4.1 Head

4.1.1 结构说明

  1. HEAD
  2. CURRENT: 32
  3. NONCE: 4
  4. PREVIOUS: 32 -> completely zero if genesis block
  5. TARGET: 32
  6. TIME: 4
  7. VALENCE: 4

4.1.2 程序数据结构

Head的长度固定是108字节, 所以不需要保存长度.

字段说明 current nounce previous target time valence
说明 BODY的sha256输出,当前block的ID 挖矿难度 前个区块的ID 越大难度越小 ?时间 交易个数
长度(字节) 32 4 32 32 4 4

nounce , target 用于pow, 在链的最初不需要pow, 当有很多个节点创造block时才用到pow,

4.1.3 程序代码

  1. unsigned char *get_head(unsigned char *root)
  2. {
  3. unsigned char *complete, *y;
  4. unsigned int *x;
  5. complete = malloc(104);
  6. y = malloc(32);
  7. memcpy(y, root, 32);
  8. memcpy(complete, y, 32);
  9. x = malloc(4);
  10. *x = 0;
  11. memcpy(complete + 32, x, 4);
  12. y = malloc(32);
  13. memset(y, 0, 32);
  14. memcpy(complete + 36, y, 32);
  15. y = malloc(32);
  16. memset(y, 255, 32);
  17. memcpy(complete + 68, y, 32);
  18. x = malloc(4);
  19. *x = time(0);
  20. memcpy(complete + 100, x, 4);
  21. return complete;
  22. }

4.2 Body

4.2.1 Transaction-Input

4.2.1.1 结构说明

  1. TRANSACTION #1 // 第一个区块.
  2. INPUTS: 1
  3. INDEX: 4 -> completely zero
  4. PUBLIC: 0
  5. SIGNATURE: 0
  6. TRANSACTION: 32 -> completely zero
  7. TRANSACTION #2,#3,... // 之后的区块
  8. INPUTS: 1个或者以上
  9. INDEX: 4
  10. PUBLIC: linghuo
  11. SIGNATURE: linghuo
  12. TRANSACTION: 32

4.2.1.2 程序数据结构

字段名 A (总长) index B public C Signature Transaction的sha256
说明 总长 第几个Input public长度 公钥 签名长度 签名 交易的hash, merkle root
长度(字节) 4 4 4 B 4 C 32

4.2.1.3 程序代码

  1. unsigned char *get_input(unsigned int *total)
  2. {
  3. // A index B public C signature transaction
  4. char *private, *public, *complete;
  5. int length;
  6. int *x;
  7. unsigned char *y;
  8. private = get_private(&length);
  9. public = get_public(&length, private);
  10. complete = malloc(*total = 48 + length);
  11. x = malloc(4);
  12. *x = 48 + length;
  13. memcpy(complete, x, 4); // 放置总长
  14. x = malloc(4);
  15. *x = 0;
  16. memcpy(complete + 4, x, 4); //放置Index长
  17. x = malloc(4);
  18. *x = length;
  19. memcpy(complete + 8, x, 4); // 放置public的长度
  20. y = malloc(length);
  21. memcpy(y, public, length);
  22. memcpy(complete + 12, y, length); // 放置公钥public
  23. //!! 应该放置signature 的长度, 和 signature, 因为还未讲到signature的用法, 暂时先不放.
  24. x = malloc(4);
  25. *x = 0;
  26. memcpy(complete + 12 + length, x, 4); //放置Signature长度.
  27. y = malloc(32);
  28. memset(y, 0, 32);
  29. memcpy(complete + 16 + length, y, 32); // 放置Transaction ??
  30. return complete;
  31. }

4.2.2 Transaction-Output

4.2.2.1 结构说明

第1个交易中的Output

  1. OUTPUTS: 1
  2. ADDRESS: 大小不定 -> 矿工地址
  3. AMOUNT: 8字节 -> 100或者50

第2+个交易中的Output

  1. OUTPUTS: 1
  2. ADDRESS: 大小不定 -> 地址
  3. AMOUNT: 8字节

4.2.2.2 程序数据结构

字段名 A B Address Amount
说明 总长度 地址长度 交易地址 交易数量
长度(字节) 4 4 B 8

4.2.2.3 代码

  1. unsigned char *get_output(unsigned int *total)
  2. {
  3. unsigned char *private, *public, *complete, *y;
  4. unsigned int length, *x, z;
  5. private = get_private(&length);
  6. public = get_public(&length, private);
  7. // len_A len_B address amount
  8. // 4 + 4 + B + 8
  9. complete = malloc(*total = 16 + length);
  10. x = malloc(4);
  11. *x = 16 + length;
  12. memcpy(complete, x, 4); // 设置总长 A
  13. x = malloc(4);
  14. *x = length;
  15. memcpy(complete + 4, x, 4); // 设地址长度 B
  16. y = malloc(length);
  17. memcpy(y, public, length);
  18. memcpy(complete + 8, y, length); // 设置地址, 暂时把公钥作为地址
  19. y = malloc(8);
  20. z = 1000;
  21. memcpy(y, &z, 4);
  22. memset(y + 4, 0, 4);
  23. memcpy(complete + 8 + length, y, 8); // 设置8字节的交易数量
  24. return complete;
  25. }

4.2.3 Transaction

4.2.3.1 结构说明

  1. TRANSACTION #1
  2. INPUTS: 1
  3. INDEX: 4 -> completely zero
  4. PUBLIC: 0
  5. SIGNATURE: 0
  6. TRANSACTION: 32 -> completely zero
  7. OUTPUTS: 1
  8. ADDRESS: linghuo -> miner's address
  9. AMOUNT: 8 -> 50 huozhe 100
  10. TRANSACTION #2
  11. TRANSACTION #3
  12. INPUTS: yige huozhe yishang
  13. INDEX: 4
  14. PUBLIC: linghuo
  15. SIGNATURE: linghuo
  16. TRANSACTION: 32
  17. OUTPUTS: yige huozhe yishang
  18. ADDRESS: linghuo
  19. AMOUNT: 8

4.2.3.2 程序数据结构

Transaction

字段名 A B C Input* Output*
说明 总长度(含自己) 输入个数 输出个数 输入列表 输出列表
长度(字节) 4 4 4 B C

结构有变更.

4.2.3.3 程序代码(旧代码,待更改)

  1. unsigned char *get_transaction(unsigned int *total)
  2. {
  3. unsigned char *input, *output, *complete, *y;
  4. unsigned int length_input, length_output, *x;
  5. input = get_input(&length_input);
  6. output = get_output(&length_output);
  7. complete = malloc(*total = 12 + length_input + length_output);
  8. x = malloc(4); // A
  9. *x = 12 + length_input + length_output;
  10. memcpy(complete, x, 4);
  11. x = malloc(4);
  12. *x = 1; // B, 只有1个输入
  13. memcpy(complete + 4, x, 4);
  14. x = malloc(4);
  15. *x = 1; // C 只有一个输出
  16. memcpy(complete + 8, x, 4);
  17. y = malloc(length_input); // input
  18. memcpy(y, input, length_input);
  19. memcpy(complete + 12, y, length_input);
  20. y = malloc(length_output); // output
  21. memcpy(y, output, length_output);
  22. memcpy(complete + 12 + length_input, y, length_output);
  23. return complete;
  24. }

4.4 程序开发实现

4.4.1 常用函数设计

为了方便处理区块字段, 设计了相关函数. 简化常见的操作.

  1. char *string_create(char *old, int length)
  2. char *string_create_improper(char *old)
  3. char *string_create_progression(int a)
  4. int string_measure(char *buffer)
  5. void string_update(char *object, char *buffer, int length)
  6. void string_update_4(char *object, int quantity)
  7. void string_update_8(char *object, uint64_t quantity)
  8. void string_update_initial(char *object, char *initial)
  9. char *string_eject(char *object)
  10. int scan(char *source)

4.4.2 区块及示例区块数据生成

需要说明的是, 因为老师对随机数字比字母单词更敏感,所以实例程序中的变量很多采用了数字来表示. 并无其他深意.

  1. #define TFM_DESC
  2. #include "stdio.h"
  3. #include "stdlib.h"
  4. #include "string.h"
  5. #include "tfm.h"
  6. #include "tomcrypt.h"
  7. char *string_create(char *old, int length)
  8. {
  9. char *new;
  10. int *_6157;
  11. new = malloc(length + 4) + 4;
  12. memcpy(new, old, length);
  13. _6157 = (int *) (new - 4);
  14. *_6157 = length;
  15. return new;
  16. }
  17. char *string_create_improper(char *old)
  18. {
  19. char *new;
  20. int *_7193;
  21. new = malloc(strlen(old) + 4) + 4;
  22. memcpy(new, old, strlen(old));
  23. _7193 = (int *) (new - 4);
  24. *_7193 = strlen(old);
  25. return new;
  26. }
  27. char *string_create_progression(int a)
  28. {
  29. char *c;
  30. int *_3919;
  31. c = malloc(a + 4) + 4;
  32. _3919 = (int *) (c - 4);
  33. *_3919 = 0;
  34. return c;
  35. }
  36. int string_measure(char *buffer)
  37. {
  38. int *_4721;
  39. _4721 = (int *) (buffer - 4);
  40. return *_4721;
  41. }
  42. void string_update(char *object, char *buffer, int length)
  43. {
  44. int *_9492;
  45. _9492 = (int *) (object - 4);
  46. memcpy(object + *_9492, buffer, length);
  47. *_9492 += length;
  48. }
  49. void string_update_4(char *object, int quantity)
  50. {
  51. int *_7751, *_2888;
  52. _7751 = (int *) (object - 4);
  53. _2888 = (int *) (object + *_7751);
  54. *_2888 = quantity;
  55. *_7751 += 4;
  56. }
  57. void string_update_8(char *object, uint64_t quantity)
  58. {
  59. int *_7751;
  60. uint64_t *_2888;
  61. _7751 = (int *) (object - 4);
  62. _2888 = (uint64_t *) (object + *_7751);
  63. *_2888 = quantity;
  64. *_7751 += 8;
  65. }
  66. void string_update_initial(char *object, char *initial)
  67. {
  68. int *_8478, *_5970;
  69. _8478 = (int *) (object - 4);
  70. _5970 = (int *) initial;
  71. memcpy(object + *_8478, initial, *_5970);
  72. *_8478 += *_5970;
  73. }
  74. char *string_eject(char *object)
  75. {
  76. char *new;
  77. int *_6558;
  78. _6558 = (int *) (object - 4);
  79. new = malloc(*_6558);
  80. memcpy(new, object, *_6558);
  81. return new;
  82. }
  83. char *get_maximal()
  84. {
  85. char *digest;
  86. digest = malloc(32);
  87. memset(digest, 255, 32);
  88. return digest;
  89. }
  90. char *get_minimal()
  91. {
  92. char *digest;
  93. digest = malloc(32);
  94. memset(digest, 0, 32);
  95. return digest;
  96. }
  97. int scan(char *source)
  98. {
  99. int *size;
  100. size = (int *) source;
  101. return *size;
  102. }
  103. char *get_file(char *path) {
  104. FILE *file;
  105. int length;
  106. char *contents;
  107. file = fopen(path, "r+");
  108. fseek(file, 0, SEEK_END);
  109. length = ftell(file);
  110. fseek(file, 0, SEEK_SET);
  111. contents = malloc(length + 1);
  112. fread(contents, 1, length, file);
  113. fclose(file);
  114. return contents;
  115. }
  116. // same info, after ecc signature, output different sig length because of random number.
  117. char *get_signature(char *object, char *private)
  118. {
  119. prng_state _1307;
  120. ecc_key _1317;
  121. int _1648;
  122. char *_5497;
  123. _5497 = malloc(1000);
  124. _1648 = 1000;
  125. ecc_import(private, string_measure(private), &_1317);
  126. ecc_sign_hash(object, string_measure(object), _5497, &_1648, &_1307, find_prng("sprng"), &_1317);
  127. return string_create(_5497, _1648);
  128. }
  129. unsigned char *get_private(unsigned int *length)
  130. {
  131. prng_state random;
  132. ecc_key key;
  133. unsigned char *buffer;
  134. buffer = malloc(*length = 1000);
  135. ecc_make_key(&random, find_prng("sprng"), 32, &key);
  136. ecc_export(buffer, length, PK_PRIVATE, &key);
  137. return buffer;
  138. }
  139. unsigned char *get_public(unsigned int *length, unsigned char *private)
  140. {
  141. ecc_key key;
  142. unsigned char *buffer;
  143. ecc_import(private, *length, &key);
  144. buffer = malloc(*length = 1000);
  145. ecc_export(buffer, length, PK_PUBLIC, &key);
  146. return buffer;
  147. }
  148. char *build_input(int _8626, char *_5409, char *_4051, char *_3775)
  149. {
  150. char *_9016;
  151. int *_1933;
  152. _9016 = malloc(48 + string_measure(_5409) + string_measure(_4051));
  153. _1933 = (int *) _9016;
  154. *_1933 = 48 + string_measure(_5409) + string_measure(_4051);
  155. _1933 = (int *) (_9016 + 4);
  156. *_1933 = _8626;
  157. _1933 = (int *) (_9016 + 8);
  158. *_1933 = string_measure(_5409);
  159. memcpy(_9016 + 12, _5409, string_measure(_5409));
  160. _1933 = (int *) (_9016 + 12 + string_measure(_5409));
  161. *_1933 = string_measure(_4051);
  162. memcpy(_9016 + 16 + string_measure(_5409), _4051, string_measure(_4051));
  163. memcpy(_9016 + 16 + string_measure(_5409) + string_measure(_4051), _3775, 32);
  164. return _9016;
  165. }
  166. char *build_output(char *_7095, uint64_t _8432)
  167. {
  168. char *_3516;
  169. int *_8347;
  170. uint64_t *_9910;
  171. _3516 = malloc(16 + string_measure(_7095));
  172. _8347 = (int *) _3516;
  173. *_8347 = 16 + string_measure(_7095);
  174. _8347 = (int *) (_3516 + 4);
  175. *_8347 = string_measure(_7095);
  176. memcpy(_3516 + 8, _7095, string_measure(_7095));
  177. _9910 = (uint64_t *) (_3516 + 8 + string_measure(_7095));
  178. *_9910 = _8432;
  179. return _3516;
  180. }
  181. char *get_sha256(char *buffer, int size)
  182. {
  183. hash_state resource;
  184. char *digest;
  185. digest = malloc(32);
  186. sha256_init(&resource);
  187. sha256_process(&resource, buffer, size);
  188. sha256_done(&resource, digest);
  189. return digest;
  190. }
  191. char *get_md5(char *buffer, int size)
  192. {
  193. hash_state resource;
  194. char *digest;
  195. digest = malloc(16);
  196. md5_init(&resource);
  197. md5_process(&resource, buffer, size);
  198. md5_done(&resource, digest);
  199. return digest;
  200. }
  201. char *get_merkle_root(char *old, int size)
  202. {
  203. char *new, output[32], input[64];
  204. int index;
  205. if (size == 1) {
  206. return old;
  207. }
  208. if (size % 2) {
  209. new = malloc(32 * (size + 1));
  210. memcpy(new, old, size * 32);
  211. memcpy(new + size * 32, old + (size - 1) * 32, 32);
  212. return get_merkle_root(new, size + 1);
  213. }
  214. new = malloc(32 * size / 2);
  215. for (index = 0; index < size; index += 2) {
  216. memcpy(input, old + index * 32, 64);
  217. memcpy(new + (index / 2) * 32, get_sha256(input, 64), 32);
  218. }
  219. return get_merkle_root(new, size / 2);
  220. }
  221. void print_digest(char *digest)
  222. {
  223. int index;
  224. for (index = 0; index < 32; index++)
  225. printf("%02hhx", digest[index]);
  226. printf("%c", 10);
  227. }
  228. // ------------------
  229. char *transaction_7159(int A, char *B, char *C, char *D, char *lichangli, char *panpeng)
  230. {
  231. char *input_0, *output_0, *output_1, *transaction;
  232. input_0 = build_input(A, B, C, D);
  233. output_0 = build_output(lichangli, 99);
  234. output_1 = build_output(panpeng, 1);
  235. transaction = string_create_progression(12 + scan(input_0) + scan(output_0) + scan(output_1));
  236. string_update_4(transaction, 12 + scan(input_0) + scan(output_0) + scan(output_1));
  237. string_update_4(transaction, 1);
  238. string_update_4(transaction, 2);
  239. string_update(transaction, input_0, scan(input_0));
  240. string_update(transaction, output_0, scan(output_0));
  241. string_update(transaction, output_1, scan(output_1));
  242. return transaction;
  243. }
  244. char *block_3930(char *A)
  245. {
  246. char *block;
  247. block = string_create_progression(108 + string_measure(A));
  248. string_update(block, get_sha256(A, string_measure(A)), 32);
  249. string_update_4(block, 0);
  250. string_update(block, get_minimal(), 32);
  251. string_update(block, get_maximal(), 32);
  252. string_update_4(block, time(0));
  253. string_update_4(block, 1);
  254. string_update(block, A, string_measure(A));
  255. return block;
  256. }
  257. char *block_4479(char *previous, char *A, char *B)
  258. {
  259. char *block, *tree;
  260. tree = string_create_progression(64);
  261. string_update(tree, get_sha256(A, string_measure(A)), 32);
  262. string_update(tree, get_sha256(B, string_measure(B)), 32);
  263. block = string_create_progression(108 + string_measure(A) + string_measure(B));
  264. string_update(block, get_merkle_root(tree, 2), 32);
  265. string_update_4(block, 0);
  266. string_update(block, previous, 32);
  267. string_update(block, get_maximal(), 32);
  268. string_update_4(block, time(0));
  269. string_update_4(block, 2);
  270. string_update(block, A, string_measure(A));
  271. string_update(block, B, string_measure(B));
  272. return block;
  273. }
  274. char *transaction_8629(char *lichangli)
  275. {
  276. char *input_0, *output_0, *progression;
  277. input_0 = build_input(0, string_create_improper(""), string_create_improper(""), get_minimal());
  278. output_0 = build_output(lichangli, 100);
  279. progression = string_create_progression(12 + scan(input_0) + scan(output_0));
  280. string_update_4(progression, 12 + scan(input_0) + scan(output_0));
  281. string_update_4(progression, 1);
  282. string_update_4(progression, 1);
  283. string_update(progression, input_0, scan(input_0));
  284. string_update(progression, output_0, scan(output_0));
  285. return progression;
  286. }
  287. char *transaction_4140(char *lichangli)
  288. {
  289. char *input_0, *output_0, *progression;
  290. input_0 = build_input(0, string_create_improper(""), string_create_improper(""), get_minimal());
  291. output_0 = build_output(lichangli, 100);
  292. progression = string_create_progression(12 + scan(input_0) + scan(output_0));
  293. string_update_4(progression, 12 + scan(input_0) + scan(output_0));
  294. string_update_4(progression, 1);
  295. string_update_4(progression, 1);
  296. string_update(progression, input_0, scan(input_0));
  297. string_update(progression, output_0, scan(output_0));
  298. return progression;
  299. }

4.4.3 示例数据写入调用

完成了示例数据的写入, 就方便后面开发读取和验证的部分的代码的测试了.

  1. int main(int count, char **arguments)
  2. {
  3. ltc_mp = tfm_desc;
  4. register_prng(&sprng_desc);
  5. register_hash(&sha256_desc);
  6. char *A, *B, *C, *BLOCK_A, *BLOCK_B;
  7. char *_6301, *_1604, *_1215;
  8. char *buffer;
  9. int length;
  10. char *panpeng_address, *panpeng_public, *lichangli_address, *lichangli_public, *lichangli_private;
  11. _6301 = "MEwDAgcAAgEgAiEAy4Dqak+QdoTjLOneFcw45XLVvRo1pxlurO7CdnSiEmkCIEHKqUkf236XXyybfJWX8dhvHKJXHwJ2TKJ6f2J78OIiMEwDAgcAAgEgAiEAy
  12. 4Dqak+QdoTjLOneFcw45XLVvRo1pxlurO7CdnSiEmkCIEHKqUkf236XXyybfJWX8dhvHKJXHwJ2TKJ6f2J78OIi";
  13. _1604 = "MEwDAgcAAgEgAiB/XlZGVRCrgg1QoZpLXP25dBxfE+l53GcrQT+rnOyMtQIhAPjOmLLKCkZeuk378KlQCLXGYcx3ZZNpYt2xqPTS6BC/";
  14. _1215 = "MG8DAgeAAgEgAiB/XlZGVRCrgg1QoZpLXP25dBxfE+l53GcrQT+rnOyMtQIhAPjOmLLKCkZeuk378KlQCLXGYcx3ZZNpYt2xqPTS6BC/AiEAuUgmCNAsw2ElO
  15. 5hxpvAzJpKcdSuyiHV84R2jTPFVu7o=";
  16. buffer = malloc(1000);
  17. length = 1000;
  18. base64_decode(_6301, strlen(_6301), buffer, &length);
  19. panpeng_public = string_create(buffer, length);
  20. length = 1000;
  21. base64_decode(_1604, strlen(_1604), buffer, &length);
  22. lichangli_public = string_create(buffer, length);
  23. length = 1000;
  24. base64_decode(_1215, strlen(_1215), buffer, &length);
  25. lichangli_private = string_create(buffer, length);
  26. panpeng_address = string_create(get_md5(panpeng_public, 32), 16);
  27. lichangli_address = string_create(get_md5(lichangli_public, 32), 16);
  28. A = transaction_8629(lichangli_address);
  29. B = transaction_4140(lichangli_address);
  30. C = transaction_7159(1, lichangli_public, get_signature(A, lichangli_private), get_sha256(A, string_measure(A)), lichangli_address
  31. , panpeng_address);
  32. BLOCK_A = block_3930(A);
  33. BLOCK_B = block_4479(get_sha256(BLOCK_A, string_measure(BLOCK_A)), B, C);
  34. write(1, BLOCK_B, string_measure(BLOCK_B));
  35. }

5. 区块节点读取验证与挖矿

5.1 merkle tree 说明

Hash的计算简要示意
image_1btodkb4qm17lf2fj1q96gr13.png-52.9kB
交易的hash计算与区块简要示意
image_1btodfhca5dr15cg1s2760lm919.png-41.9kB

5.1.1 递归函数定义

递归计算merkle root
先计算单个.
然后计算奇数的hash,
计算偶数的hash

  1. pseudo code, author by Lijun
  2. merkle_root(arr[])
  3. if(count(arr[]) ==1 ) return arr[0];
  4. if(count(arr[]) %2 )
  5. return sha256(merkle_root(arr[0,n-2]), arr[n-1])
  6. else
  7. return shar256(merkle_root(arr[0,n/2-1]), merkle_root(arr[n/2, n-1]);

只有一个交易,merkle root就是对这个交易的hash.

  • get_merkle_root(X) = X
  • get_merkle_root(X0 , X1 , …… , X2n ) = get_merkle_root(X0 ,X1 ,…… ,X2n,X2n)
  • get_merkle_root(X0 , X1 , …… , X2n-1 ) = get_merkle_root(SHA256(X0+X1), SHA256(X2+X3) ……)
  1. function(x) {
  2. if (count(x) == 1 ) return x;
  3. if (count(x) %2) x.push[x, (
  4. }

5.1.2 php递归实现代码

  1. <?php
  2. function get_lines_file($file)
  3. {
  4. $result = array();
  5. $contents = file_get_contents($file);
  6. $contents = explode(chr(10), $contents); //用换行符分割
  7. // linux 放10, windows会放13,10作为换行,所以删掉13
  8. foreach ($contents as $item) {
  9. $item = str_replace(chr(13), '', $item); // 去掉char13
  10. if (strlen($item) > 0)
  11. array_push($result, $item);
  12. }
  13. return $result;
  14. }
  15. /* 生成hash. 可以输出存到 文件里.
  16. $digests = array();
  17. foreach(range(1,100) as $number)
  18. $digests[] = hash('sha256', rand());
  19. */
  20. $x = get_lines_file('digests.txt');
  21. var_dump(get_Merkle_root($x));
  22. function get_Merkle_root($digests)
  23. {
  24. if (count($digests) == 1) {
  25. echo sprintf('Case #1: %d%c', count($digests), 10);
  26. return $digests[0];
  27. }
  28. if (count($digests) % 2) { // 奇数
  29. echo sprintf('Case #2: %d%c', count($digests), 10);
  30. $item = $digests[count($digests) - 1];
  31. array_push($digests, $item); // push, 把最后1个item复制
  32. return get_Merkle_root($digests);
  33. }
  34. echo sprintf('Case #3: %d%c', count($digests), 10);
  35. for ($i = 0, $s = count($digests) / 2; $i < $s; $i++) {
  36. $a = array_shift($digests); // 从左侧移出
  37. $b = array_shift($digests); // 组成一对计算hash.
  38. array_push($digests, hash('sha256', $a . $b)); //从右侧插入
  39. }
  40. return get_Merkle_root($digests);
  41. /* 另外一种方法, 新建一个数组reduced存放
  42. $i = 0;
  43. while($i < count($digests)){
  44. $merged= sprintf('%s%s',$digests[i[,$digests[i+1]);
  45. array_push($reduced, hash('sha256',$merged));
  46. $i += 2;
  47. }
  48. return get_Merkle_root($reduced);
  49. */
  50. }

digests.txt的内容是100个随机数的hash值, 每行一个hash值.

  1. $ head -3 digests.txt
  2. c5c77f852587da8a14d163e9be251c79590ac1354da79397b44b7e23e55d7470
  3. 4247c422e39497fc67e527dffe0ccbcd19dc9be0bd12ed2c9bc78ae4f64ce369
  4. e9f07edbdbdc7403a93903840a096944b7194d38a73b497531fb65a56541cab7

5.2 区块节点读取说明

创造节点之后, 读取区块相关内容信息, 并进行验证, 确认都是正确的.

再次回顾下数据结构:

Head的长度固定, 所以不需要保存长度. 这里设计为104

字段说明 current nounce previous target time
说明 BODY的sha256输出,当前block的ID 挖矿难度 前个区块的ID 越大难度越小 ?时间
长度(字节) 32 4 32 32 4

Transaction 旧设计

字段名 A B Input* C Output*
说明 总长度 所有输入长度 输入 所有output长度 多个输出
长度(字节) 4 4 B 4 C

Transaction 新设计

字段名 A B C Input* Output*
说明 总长度(含自己) 输入个数 输出个数 输入列表 输出列表
长度(字节) 4 4 4 B C

Head 后面跟多个Transaction. 其中第1个Transaction是创始交易, 用于矿工奖励.

Transaction
为了方便, 将上表中的 B, Input*, C, Output* 统一表示为后继内容Content.

字段名 Head Transaction#1 Transaction#2 T#3 ...
说明 头部 总长度A和后继内容 总长度A和后继内容 总长度A和后继内容 ...
结构 Head A,Content A,Content A,Content ...
长度(字节) 104 A A A ...

5.2.1 基于字节的移动来读取内容

取得区块的生字节后, 可以通过指针来回移动, 获取相关内容. 指针到达的位置就是整数int长度的位置, 取*就可以得到其长度.

x+104, // 到达body,第一个交易.
x +104 +(*) // 达到第2个交易.
x +104 +(*) + (*) // 达到第2个交易.

C语言实现:

  1. x = x + 104;
  2. x = x + (*x);
  3. x = x + (*x);

5.2.2 指针移动获得区块的不同变量

回顾Input的结构:
INPUT := A, INDEX, B, PUBLIC, C, SIGNATURE, TRANSACTION

通过指针移动获取相应变量地址

  1. unsigned *A, *B, *C
  2. A = input
  3. B = input + 8
  4. C = input + 12 + B

5.2.3 对区块里有多少交易进行计数

  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #include "string.h"
  4. // 这里加了length存 读取出文件内容的长度.
  5. unsigned char *get_file(char *path, long *length) {
  6. FILE *file;
  7. unsigned char *contents;
  8. file = fopen(path, "r+");
  9. fseek(file, 0, SEEK_END);
  10. *length = ftell(file);
  11. fseek(file, 0, SEEK_SET);
  12. contents = malloc((size_t)*length);
  13. fread(contents, 1, (size_t)*length, file);
  14. fclose(file);
  15. return contents;
  16. }
  17. unsigned int slice(unsigned char *cursor, unsigned int length)
  18. {
  19. unsigned char *limit;
  20. unsigned int *X;
  21. unsigned int count;
  22. limit = cursor + length; // 尾部
  23. cursor += 104;
  24. count = 0;
  25. while (cursor < limit) {
  26. X = (unsigned int *)cursor; //指针类型转换
  27. cursor += *X; // 跳到下个交易
  28. count++;
  29. }
  30. return count;
  31. }
  32. int main(int count, char **arguments)
  33. {
  34. unsigned char *block;
  35. unsigned int length;
  36. block = get_file(arguments[1], &length);
  37. printf("%d%c", slice(block, length), 10);
  38. }

5.2.2 构造链表来读取交易

image_1btodtl5s5t219q3dqaauf1gkl20.png-222kB

在上一个slice的基础上, 一边遍历,一边分配空间, 同时创造linklist来指向内容空间.

  1. unsigned int slice(unsigned char *cursor, unsigned int length)
  2. {
  3. unsigned char *limit, *transaction;
  4. unsigned int *X;
  5. void *list, *link;
  6. unsigned int count;
  7. limit = cursor + length; // 尾部
  8. cursor += 104;
  9. count = 0;
  10. while (cursor < limit) {
  11. X = (unsigned int *)cursor; //指针类型转换
  12. transaction = malloc(*X + 4) + 4; //获取新分配的内容空间的交易内容地址起始位置
  13. memcpy(transaction, cursor, *X); //保存内容, 长度为*X,即交易长度
  14. memcpy(transaction-4, X, 4); // 保存内容的长度.
  15. cursor += *X;
  16. count++;
  17. // 相当2个4字节指针,前一个装内容地址, 后一个装后list的地址
  18. // 这是一种比较粗糙的方式来构造linklist, 后面会介绍通过函数来构造.
  19. link = malloc(8);
  20. memcpy(link, transaction, 4);
  21. memcpy(link + 4, list, 4);
  22. list = link;
  23. }
  24. return count;
  25. }

5.3 区块节点存储的读取实现

5.3.1 区块链结构存储的处理程序规划

  1. storage.add_block( $storage, $substance)
  2. storage.remove_block($storage, $identify)
  3. storage.get_block($storage, $identify)
  4. storage.load($storage, $identify) // 放内存
  5. storage.unload($storage, $identify) // 从内存中卸载. 放硬盘上 缓存
  6. storage.get_transaction($storage, $identify);
  7. //
  8. int *storage_load read_file() get_file()
  9. int *storage_unload write_file(path, substance, length)
  10. char *storage_get_block

可以用heap list vector or tree 来落实上面的函数, 在效率上会有差别, 但是效果一样.

5.3.2 如果是网络读取,则tcp接收区块.

1) 阅读 108个字节, 保存valence为Y
2) 读 4个字节, 保存为X
3) 读 X 个字节
4) 用副函数来确认此交易格式
5) 递归向 步骤2 一共 Y次
6) 做验证. (格式已经确认)

5.3.3 区块节点存储设计开发详细说明

规划设计:
Storage 的结构
// 容量, 创始的指针, 文件路径的指针, 区块数量, 区块1, 2...
// CAPACITY, GENESIS, PATH, VALENCE, RECORD #1, RECORD #2, ...
// 4, 4, 4, 4, 4 (block#1 pointer), 4 (block#2 pointer)..

block# pointer ---> RECORD
// RECORD := IDENTITY, LENGTH, SUBSTANCE

/*
CAPACITY, GENESIS, PATH, VALENCE, RECORD #1, RECORD #2, ...
RECORD := IDENTITY, LENGTH, SUBSTANCE
*/

源代码来自15节课 storage.c

  1. char *storage_get(char *storage, char *identity, int *length)
  2. {
  3. char *_2250, **_9000, **_4708;
  4. int *_5756;
  5. char **cursor, **boundary;
  6. int *valence;
  7. char **_0000;
  8. valence = (int *) (storage + 12);
  9. cursor = (char **) (storage + 16);
  10. boundary = (char **) (storage + 16 + *valence * 4);
  11. while (cursor < boundary) {
  12. _0000 = (char **) cursor;
  13. _9000 = (char **) *_0000;
  14. _5756 = (int *) (*_0000 + 4);
  15. _4708 = (char **) (*_0000 + 8);
  16. printf("while: %d%c", *_5756, 10);
  17. if (memcmp(identity, *_9000, 32) == 0) {
  18. printf("match was found%c", 10);
  19. _2250 = malloc(*length = *_5756);
  20. memcpy(_2250, *_4708, *_5756);
  21. return _2250;
  22. }
  23. cursor++;
  24. }
  25. return 0;
  26. }
  27. char *storage_create(int capacity, char *genesis, char *path)
  28. {
  29. char *_9877, *_1767;
  30. char **_2789;
  31. int *_1046;
  32. _9877 = malloc(16 + 4 * capacity);
  33. _1046 = (int *) _9877;
  34. *_1046 = capacity;
  35. _1767 = malloc(32);
  36. memcpy(_1767, genesis, 32);
  37. _2789 = (char **) (_9877 + 4);
  38. *_2789 = _1767;
  39. _1767 = malloc(strlen(path));
  40. strcpy(_1767, path);
  41. _2789 = (char **) (_9877 + 8);
  42. *_2789 = _1767;
  43. _1046 = (int *) (_9877 + 12);
  44. *_1046 = 0;
  45. return _9877;
  46. }
  47. void storage_add(char *storage, char *identity, char *substance, int length)
  48. {
  49. char **_9646, **_8035;
  50. int *capacity, *valence, *_4683;
  51. char *_7990, *record;
  52. valence = (int *) (storage + 12);
  53. _9646 = (char **) (storage + 16 + *valence * 4);
  54. char **_1616, **_7413;
  55. int *_9039;
  56. record = malloc(12);
  57. _1616 = (char **) record;
  58. _9039 = (int *) (record + 4);
  59. _7413 = (char **) (record + 8);
  60. *_1616 = malloc(32);
  61. memcpy(*_1616, identity, 32);
  62. *_9039 = length;
  63. *_7413 = malloc(32);
  64. memcpy(*_7413, substance, length);
  65. *_9646 = record;
  66. *valence += 1;
  67. }

调用链区块节点存储

  1. int main(int count, char **arguments)
  2. {
  3. ltc_mp = tfm_desc;
  4. register_prng(&sprng_desc);
  5. register_hash(&sha256_desc);
  6. char *storage, *substance;
  7. int *valence, length;
  8. storage = storage_create(400, get_minimal(), "/tmp/blocks");
  9. valence = (int *) (storage + 12);
  10. printf("valence: %d%c", *valence, 10);
  11. storage_add(storage, get_minimal(), "hello", 6);
  12. valence = (int *) (storage + 12);
  13. printf("valence: %d%c", *valence, 10);
  14. storage_add(storage, get_maximal(), "goodbye", 8);
  15. valence = (int *) (storage + 12);
  16. printf("valence: %d%c", *valence, 10);
  17. int *_3895;
  18. int *_9394;
  19. char **_8900;
  20. _3895 = (int *) (storage);
  21. printf("inspection: %d%c", *_3895, 10);
  22. _3895 = (int *) (storage + 4);
  23. printf("inspection: %d%c", *_3895, 10);
  24. _3895 = (int *) (storage + 8);
  25. printf("inspection: %d%c", *_3895, 10);
  26. _3895 = (int *) (storage + 12);
  27. printf("inspection: %d%c", *_3895, 10);
  28. _3895 = (int *) (storage + 16);
  29. printf("inspection: %d%c", *_3895, 10);
  30. _3895 = (int *) (storage + 20);
  31. printf("inspection: %d%c", *_3895, 10);
  32. _3895 = (int *) (storage + 24);
  33. printf("inspection: %d%c", *_3895, 10);
  34. _3895 = (int *) (storage + 28);
  35. printf("inspection: %d%c", *_3895, 10);
  36. _8900 = (char **) (storage + 20);
  37. _9394 = (int *) (*_8900 + 4);
  38. printf("inspection: %d%c", *_9394, 10);
  39. substance = storage_get(storage, get_minimal(), &length);
  40. printf("storage_get(): %d%c", length, 10);
  41. printf("storage_get(): %s%c", substance, 10);
  42. substance = storage_get(storage, get_maximal(), &length);
  43. printf("storage_get(): %d%c", length, 10);
  44. printf("storage_get(): %s%c", substance, 10);
  45. }

5.3.4 改进:存储改为hash实现

如果区块链的存储要更改,改为效率更高一些, 可以改为用hashtable.
(组成: 256个bucket, 指针列表, 元数据.) 通过hash找到对应bucket, 搜索时为O(lg(n))的复杂度.
image_1bv4ha57l1f6r4sm18j81140ogs9.png-671.1kB

5.4 区块节点验证说明

创造节点之后,
* 读取区块相关内容信息, 并进行验证, 确认都是正确的.
* 验证第2个以上的交易(input, output, transaction balance),
* 然后验证第一个交易, 还有头部.

验证:
(1) 格式
(2) 输入: 此输入是否存在; 输入的签名是否有校验
(3) 输出:
(4) 交易平衡: 输入是否多于或者等于输出的总额?
(5) 第一个交易
(6) 头部 交易的摘要是否正确? 劳动证明是否正确?

5.4.1 劳动证明与挖矿规则

劳动证明是看有没有做挖掘的过程, 挖掘的目的是为了防止一个人短时间制造大量的空区块, 也为了维持竞争性.
不同的网络上的节点, 每个区块的生产的过程, 相当于比赛的一局. 胜利者获利,其他人没有获得.

矿池联合挖, 自己制定一个规则, 矿主决定怎么分配利润.

大多数规则:
一个成员要是挖掘了接近正确的结果, 虽然无效, 也上报,
矿池主人根据劳动的难度的工作证明, 按照比例分配.
如A,B,C 分别挖掘了4,6,10的难度的工作, 则按此比例进行分配货币.
除此之外, 矿池主人还会再扣一些类似赋税.

节点与挖矿程序的沟通

BTC官方节点 和 挖矿程序 是通过 http 和 json-rpc 进行沟通, 效率比较低.
计算机更擅长生字节的处理. 需要转换.
好多矿池的程序修改或写了自己的节点程序, 直接用TCP 沟通.

5.4.2 区块的遍历与验证

5.4.2.1 验证过程

验证身部Body

要检查验证input, output, 还有transaction的正确性.

  1. 每一个input内, 查找 transaction, index 是否存在
  2. 每一个input内, 拿public, signature 和赌赢的output的address, 然后运行 ECC verify, 看true or false, false表示失败
  3. 检查 sigma intput >= sigma output , 记录剩余
  4. 检查 sigma 剩余 >= coinbase 的小费
  5. 验证头部
验证头部Head
  1. 检查时间: 必须大于上7个区块的平均时间, 为了保持区块链的时间在不断往上升.
  2. 检查target是否少于或者等于协议规定的target, target越小,难度越大
  3. 计算整个头的SHA256是否少于target, 然后检查 merkle tree
程序实现函数规划
  1. check_transaction($substance, $length)
  2. check_input($substance, $length)
  3. check_output($substance, $length)

5.4.2.2 程序实现

  1. /* 数链表的节点个数 */
  2. int count_list(void *cursor)
  3. {
  4. int count;
  5. void *Y;
  6. count = 0;
  7. while (cursor != 0)
  8. {
  9. count++;
  10. Y = cursor + 4;
  11. // cursor = (void *) *Y;
  12. }
  13. return count;
  14. }
  15. // 用于构造一对, 这里可以用于构造2个指针对, 作为链表的节点.
  16. void *build_pair(void *left, void *right)
  17. {
  18. void *pair;
  19. pair = malloc(8);
  20. memcpy(pair, &left, 4);
  21. memcpy(pair + 4, &right, 4);
  22. return pair;
  23. }
  24. /* 对于指针指向字符存长度位置的正当字符串(pascal string), 返回字符串的长度, 也可用于区块数据大小的读取. */
  25. int scan(unsigned char *source) // 返回大小
  26. {
  27. int *size;
  28. size = (int *) source;
  29. return *size;
  30. }
  31. /* 对于指针指向字符内容起始位置的正当字符串(pascal string), 返回字符串的长度, 也可用于区块数据大小的读取. */
  32. int measure(char *source)
  33. {
  34. int *length;
  35. length = (int *) (source - 4);
  36. return *length;
  37. }
  38. /* 字符串分2种,
  39. 一种是\0结尾, 不记录长度. 不能存\0, 叫做非正当字符串 improper (c string)
  40. 一种记录长度, 可以存任意字符串. 叫做正当字符串 proper (pascal string)
  41. 其中int整数存储长度, 本身占用4个字节.
  42. 下面是后一种
  43. */
  44. /* 构造包含自己长度的字符串, [length,string_content] */
  45. unsigned char *build(unsigned char *source, int length)
  46. {
  47. unsigned char *destination;
  48. destination = malloc((size_t)length + 4); //比长度大4的空间
  49. memcpy(destination, &length, 4); // 放长度
  50. memcpy(destination + 4, source, length); //放内容
  51. return destination;
  52. }
  53. unsigned char *get_file(char *path, long *length) {
  54. FILE *file;
  55. unsigned char *contents;
  56. file = fopen(path, "r+");
  57. fseek(file, 0, SEEK_END);
  58. *length = ftell(file);
  59. fseek(file, 0, SEEK_SET);
  60. contents = malloc((size_t)*length);
  61. fread(contents, 1, (size_t)*length, file);
  62. fclose(file);
  63. return contents;
  64. }
  65. /* Slice 函数用于把一个区块block切成交易.
  66. 实际内存过程展示:
  67. 形成head元素:
  68. head_pointer
  69. |
  70. [length, head_content]
  71. 形成链表的第1个节点.
  72. list_pointer --> [ head_pointer, \0]
  73. |
  74. [head]
  75. 进入while循环后, 指向block的指针依次按照transaction的大小向后移动.
  76. 添加当前读取到的交易transaction到内存中,
  77. 然后添加第2个链表节点,节点中的指针指向 transaction.
  78. [head, transaction#1, transaction#2, .... ]
  79. len:104 |len,content | len, content|...
  80. ^
  81. cursor ---> 指针按照交易大小顺序移动
  82. 读取并构建交易到内存中, 同时构建指针链表保存交易地址
  83. list_pointer --> [head_pointer, list_pointer] --> [head_pointer, \0]
  84. | |
  85. [transaction] [head]
  86. 第3个及以后的transaction以及链表依次实现.
  87. */
  88. // 返回一个指针链表的尾部. 链表中存的是指向交易和head的指针.
  89. void *slice(unsigned char *cursor, long length)
  90. {
  91. unsigned char *limit, *head;
  92. void *list;
  93. limit = cursor + length;
  94. list = 0;
  95. head = build(cursor, 104); // 内存中构造head节点
  96. printf("head pointer: %d%c", (int)head, 10);
  97. list = build_pair(head, list); // 记录head指针,list指针为pair. 形成链表的第1个节点.
  98. printf("list pointer: %d%c", (int)list, 10);
  99. cursor += 104;
  100. //
  101. while (cursor < limit) {
  102. //内存中构造transaction.
  103. unsigned char *x = build(cursor, scan(cursor));
  104. printf("transaction pointer: %d%c", (int)x, 10);
  105. //增加链表节点,
  106. list = build_pair(x, list);
  107. cursor += scan(cursor);
  108. }
  109. return list;
  110. }
  111. /*
  112. list[0] -> HEAD
  113. list[1] -> COINBASE
  114. list[2] -> TRANSACTION #2
  115. list[3] -> TRANSACTION #3...
  116. */
  117. // TRANSACTION := A, B, C, INPUT*, OUTPUT*
  118. // 这里的Transaction的定义与前面不一致了!
  119. // 得到输出的交易金额
  120. uint64_t get_output_amount(unsigned char *output)
  121. {
  122. // A B ADDRESS AMOUNT
  123. int *B;
  124. uint64_t amount; //交易金额数量.
  125. B = (int *) (output + 4);
  126. memcpy(&amount, output + 8 + *B, 8);
  127. return amount;
  128. }
  129. /*验证一个交易中的所有input,ouput的数量. */
  130. int verify(unsigned char *transaction)
  131. {
  132. int *A, *B, *C;
  133. unsigned char *cursor;
  134. int count;
  135. A = (int *) transaction;
  136. B = (int *) (transaction + 4);
  137. C = (int *) (transaction + 8);
  138. printf("%d%c", *A, 10);
  139. printf("%d%c", *B, 10);
  140. printf("%d%c", *C, 10);
  141. //8字节的整数定义.
  142. uint64_t input_total, output_total = 0; // 用于记录input,output个数.
  143. cursor = transaction + 12;
  144. count = *B;
  145. /* 查找输入的数量, 可以查看数据库??
  146. while (count--) {
  147. input_total += get_input_total(cursor); //得到输入的总数量.?
  148. cursor += scan(cursor);
  149. }
  150. */
  151. while (count--)
  152. cursor += scan(cursor);
  153. count = *C;
  154. while (count--) {
  155. output_total += get_output_amount(cursor); //得到交易金额
  156. cursor += scan(cursor);
  157. }
  158. printf("number of outputs: %d%c", *C, 10);
  159. printf("volume of outputs: %d%c", (int) output_total, 10); //交易金额
  160. return 0;
  161. }
  162. int main(int count, char **arguments)
  163. {
  164. unsigned char *block, *data;
  165. long length;
  166. void *list;
  167. char *a;
  168. block = get_file(arguments[1], &length);
  169. list = slice(block, length); // 分割block文件, 分配空间并存指针到list中.
  170. /*
  171. list += 4;
  172. */
  173. while ((int)list != 0 ) {
  174. data = (unsigned char *) *((int *) list); // 得到交易地址
  175. printf("value: %d%c", (int)data, 10);
  176. list = (void *)*((int *) (list + 4)); //下一个链表节点.
  177. printf("list: %d%c", (int)list, 10);
  178. }
  179. // verify(list + 4);
  180. }

5.5 挖矿

5.5.1 挖矿代码示例

源代码来自15节课 mining.c
还可以继续优化, 去除函数调用,直接sha256, 去除打印

  1. char *get_target(int count)
  2. {
  3. char *_2666;
  4. _2666 = malloc(32);
  5. memset(_2666, 0, count);
  6. memset(_2666 + count, 255, 32 - count);
  7. return _2666;
  8. }
  9. int main(int count, char **arguments)
  10. {
  11. // mining.
  12. ltc_mp = tfm_desc;
  13. register_prng(&sprng_desc);
  14. register_hash(&sha256_desc);
  15. char *block, *identity;
  16. int length;
  17. block = read_file(arguments[1], &length);
  18. printf("target is: ");
  19. print_digest(block + 68);
  20. printf("----%c", 10);
  21. int *_8425 = (int *) (block + 32);
  22. while (1) {
  23. identity = get_sha256(block, 108);
  24. if ((*_8425) % 144 == 0) {
  25. printf("%d: ", *_8425);
  26. print_digest(identity);
  27. }
  28. if (memcmp(identity, block + 68, 32) < 0) {
  29. printf("solution found: ");
  30. print_digest(identity);
  31. write_file(arguments[1], block, length);
  32. exit(0);
  33. }
  34. free(identity);
  35. *_8425 += 1;
  36. }
  37. }

设置block的的难度.

  1. /* set difficulty.
  2. char *substance;
  3. int length;
  4. substance = read_file("1.block", &length);
  5. memcpy(substance + 68, get_target(3), 32);
  6. memset(substance + 32, 0, 4);
  7. write_file("0.block", substance, length);
  8. */

5.5.2 挖矿过程和结果展示

  1. $ ./mining 1.block
  2. target is: 00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  3. ----
  4. 0: 09f59a9028317e4a157d5db7fee3e4ed1f837f0c84a37c792bc37db3a4073a0e
  5. 144: 84e991a6fbdc1c2340eff67bd4c2eb83bed96d8a2c410aa28bd0c1bfe3a999ea
  6. 288: 4f6471e7715489020f2fd01a290677204bea470b28c28d6bb3030c11d604cea0
  7. 432: 8e08457bd3f00f4bb246af83b42ea3c16616117a125b360cc82552bd0bb88b14
  8. solution found: 00858823157712677db364008b1b41339229497e6a49b343e664d1753c8ce47e

6. 应用和节点程序之间协议

7. 节点之间沟通

7.1 Sockets

7.1.1 Sockets 说明

C语言套接字.
建议把相关函数及参数使用记录下来.
image_1bv6uljjv1i3b1ilsip1404g6a9.png-74.9kB

image_1bto7u8pg1ot5qlgdi1cq71husg.png-23.9kB

  1. 系统呼叫:open(1),close(1),read(1),write(1)。
  2. 套接字socket:几乎所有经过网络的过程都经过socket。
  3. 每一个网络编程中,都包括连接者和被动连接者(监听者)。
    *问题:一个监听者在单线程的情况下,如何监听多个连接者?
    其中一个解决方法是排队。在监听一个连接着的时候,其他连接者被中断,排队等待。
    三个方式实现并行处理:创建新的进程、创建新的线程、使用两个特殊的系统呼叫select(2)或者poll(2)。

    • socket:制造一个新的套接字。三个参数,socket(family,type,protocol).
  1. family:家族,family的取值为2,表示互联网。
  2. type 类型,取值为1时表示tcp,取值为2时表示udptcp更安全,但是udp更快。游戏和网络视频中,一般使用udp,因为更在乎速度。一般 上午数据使用tcp,因为更在乎安全。 我们课程使用udp做一个钱包,很快,但是可能会丢包。使用udp再使用udp检查丢包,相当于是一个tcp,但是时间成本远低于tcp
  3. udp没有连接的概念,不需要使用connect函数。
  4. protocol:协议,取值为0
  5. domain socket:区域套接,不能上网的套接。
  6. netlink socket:网链套接,也不能上网,只有LInux存在,为了让程序和驱动器沟通。
  7. INET socket:即internet socket,互联网套接,我们正在使用的。
  1. 其中,x=socketfamilytypeprotocol)。
  2. 呼叫connect时,系统会卡住等待连接,所以每次做connect时,需要做多线程。这样当系统等待连接卡住的时候,其他线程不会被影响。
  3. y=connectx,目标,目标的大小)。表示是否连接成功。

7.1.2 Sockets 实现

7.1.2.1 连接者程序(不添加参数)

1.连接者程序(不添加参数)
一端使用nc -l 127.0.0.1 6004启动监听程序,另一端使用tcc -run MyConnect.c 发送消息,则可以被监听到。

  1. #include "stdio.h"
  2. #include "sys/socket.h"
  3. #include "arpa/inet.h"
  4. void main()
  5. {
  6. int s ;
  7. struct sockaddr_in a;
  8. s = socket(2,1,0);//2表示互联网,1表示tcp,0表示协议
  9. if (s == -1)//s== -1表示套接字失败
  10. exit(1);
  11. a.sin_family = 2;
  12. a.sin_port = htons(6004);
  13. a.sin_addr.s_addr = inet_addr("127.0.0.1");
  14. int f = connect(s, (struct sockaddr *) &a, sizeof a);//第一个参数是套接字的结果,第二个参数是连接目标,第三个参数是连接目标的大小。
  15. if (f == -1)
  16. exit(2);
  17. send(s,"hello ",6,0);//加空格,长度为6
  18. send(s,"world ",6,0);
  19. }

7.1.2.2 连接者程序(带参数)

    一端使用nc -l 127.0.0.1 6004启动监听程序,另一端使用tcc -run MyConnect.c 127.0.0.1 6004 发送消息,则可以被监听到。
  1. #include "stdio.h" //printf() fopen() fread() fwrite() fclose()
  2. #include "stdlib.h" //malloc(oc() free()
  3. #include "string.h" //strlen() strtok()
  4. #include "sys/socket.h" //socket
  5. #include "arpa/inet.h" //socket intnet
  6. int main (int count, char **arguments)
  7. {
  8. int s ;
  9. struct sockaddr_in a;
  10. if (count != 3){ //函数名也作为一个参数,所以一共需要三个参数。
  11. printf("error: there must be three arguments%c",10);
  12. exit(3);
  13. }
  14. s = socket(2,1,0);
  15. if (s == -1){//s==-1,unsuccessful
  16. exit(1);
  17. }
  18. a.sin_family = 2;
  19. a.sin_port = htons(atoi(arguments[2])); //atoi把参数中的字符类型转换为整型
  20. a.sin_addr.s_addr = inet_addr(arguments[1]); //两个点,是属性中的属性
  21. int f = connect(s,(struct sockaddr *) &a, sizeof a);
  22. if (f == -1)
  23. exit(2);
  24. send(s,"hello ",6,0);
  25. send(s,"world ",6,0);
  26. }

7.1.2.3 监听者程序

一端使用tcc -run MyListen.c 6006 运行监听者程序,另一端使用nc 127.0.0.1 6006 启动连接,则连接者的输入可以被监听者监听到。

  1. #include "stdio.h"
  2. #include "sys/socket.h"
  3. #include "arpa/inet.h"
  4. int main(int count, char **arguments)
  5. {
  6. int s,error,length,opponent;
  7. struct sockaddr_in a;
  8. char buffer[1000]; //长度为1000的缓存,如果发送消息的长度超过1000,则被分割为很多个长度为1000的块。
  9. s = socket(2,1,0);
  10. if (s == -1)
  11. exit(1);
  12. a.sin_family = 2;
  13. a.sin_port = htons(atoi(arguments[1]));
  14. a.sin_addr.s_addr = inet_addr("0.0.0.0"); //0.0.0.0表示可以监听任何地址。127.0.0.1表示只可以监听自己的地址。
  15. error = bind(s,(struct sockaddr *) &a,sizeof a); //bind函数的目的是设置
  16. if (error == -1)
  17. {
  18. exit(1);
  19. }
  20. //listen函数的目的是开始监听
  21. error = listen(s,1024); //1024表示允许监听的连接者的树木的最大值。第一个被监听,之后的1023个排队等待,第1025个被立即拒绝。
  22. if (error == -1)
  23. {
  24. exit(1);
  25. }
  26. //accept被呼叫之后,连接才会被收到
  27. opponent = accept(s,0,0); //后面两个参数表示对方的地址和地址长度,0,0表示不关心对方的地址
  28. if (opponent == -1)
  29. {
  30. exit(1);
  31. }
  32. while(1) //不断的循环,接听到一句话之后,依然继续链接,而不会立刻断开。
  33. {
  34. memset(buffer,0,1000);
  35. //使用缓冲之前,必须把之前的内容职位0,memset(buffer,0,1000)函数赋值为0
  36. //因为c语言新申请到的内存不是空的,是之前的垃圾信息
  37. length = recv(opponent, buffer, 1000, 0);
  38. handle();
  39. if (length == -1 || length == 0) //如果length的值为-1或者0的时候,则链接已经断开
  40. {
  41. break;
  42. }
  43. printf("%s",buffer);
  44. }
  45. }
  46. void handle()
  47. {
  48. // 商业逻辑处理过程.
  49. }

7.2 有限状态机 finite-state machine

7.2.1 php的简易示例代码和运行结果

通过php示例代码和运行过程展示来了解有限状态机的机制.

  1. $ cat 1-listen.php
  2. <?php
  3. /* 示例代码有限状态机设计:
  4. array(5410, $accumulation)
  5. array(9694, $result)
  6. */
  7. error_reporting(E_ALL); //加上这行代码就会汇报任何错误.
  8. $input = "This is the fourteenth session of the blockchain course.";
  9. $situation = array(5410, '');
  10. while (1) {
  11. $head = substr($input, 0, 1);
  12. $tail = substr($input, 1);
  13. $situation = handle_8291($situation, ord($head));
  14. var_dump($situation);
  15. if ($situation[0] == 9694)
  16. break;
  17. var_dump($input);
  18. $input = $tail;
  19. }
  20. function handle_8291($situation, $byte)
  21. {
  22. $situation[1] = $situation[1] . chr($byte);
  23. if (strlen($situation[1]) >= 24)
  24. return array(9694);
  25. return array(5410, $situation[1]);
  26. }
  27. function handle_5884($situation, $byte)
  28. {
  29. if ($situation[0] == 3786) {
  30. if ($situation[2] == 0) {
  31. $integer = unpack_integer(substr($situation[1], strlen($situation[1]) - 4));
  32. return array(1188, $situation[1], $integer, 4);
  33. }
  34. return array(3786, $situation[1] . chr($byte), $situation[2] - 1);
  35. }
  36. if ($situation[0] == 1188) {
  37. if ($situation[2] == 0) {
  38. return array(5176, $situation[1]);
  39. }
  40. if ($situation[3] == 0) {
  41. $integer = unpack_integer(substr($situation[1], strlen($situation[1]) - 4));
  42. return array(6458, $situation[1], $situation[2] - 1, $integer);
  43. }
  44. return array(1188, $situation[1] . chr($byte), $situation[2], $situation[3] - 1);
  45. }
  46. if ($situation[0] == 6458) {
  47. if ($situation[3] == 0) {
  48. }
  49. return array(3933, $situation[1] . chr($byte), $situation[2], 4);
  50. }
  51. }

运行展示有限状态机的变化过程

  1. $ php 1-listen.php
  2. array(2) {
  3. [0]=>
  4. int(5410)
  5. [1]=>
  6. string(1) "T"
  7. }
  8. string(30) "This is the blockchain course."
  9. array(2) {
  10. [0]=>
  11. int(5410)
  12. [1]=>
  13. string(2) "Th"
  14. }
  15. string(29) "his is the blockchain course."
  16. array(2) {
  17. [0]=>
  18. int(5410)
  19. [1]=>
  20. string(3) "Thi"
  21. }
  22. string(28) "is is the blockchain course."
  23. array(2) {
  24. [0]=>
  25. int(5410)
  26. [1]=>
  27. string(4) "This"
  28. }
  29. string(27) "s is the blockchain course."
  30. array(2) {
  31. [0]=>
  32. int(5410)
  33. [1]=>
  34. string(5) "This "
  35. }
  36. string(26) " is the blockchain course."
  37. array(2) {
  38. [0]=>
  39. int(5410)
  40. [1]=>
  41. string(6) "This i"
  42. }
  43. string(25) "is the blockchain course."
  44. array(2) {
  45. [0]=>
  46. int(5410)
  47. [1]=>
  48. string(7) "This is"
  49. }
  50. string(24) "s the blockchain course."
  51. array(2) {
  52. [0]=>
  53. int(5410)
  54. [1]=>
  55. string(8) "This is "
  56. }
  57. string(23) " the blockchain course."
  58. array(2) {
  59. [0]=>
  60. int(5410)
  61. [1]=>
  62. string(9) "This is t"
  63. }
  64. string(22) "the blockchain course."
  65. array(2) {
  66. [0]=>
  67. int(5410)
  68. [1]=>
  69. string(10) "This is th"
  70. }
  71. string(21) "he blockchain course."
  72. array(2) {
  73. [0]=>
  74. int(5410)
  75. [1]=>
  76. string(11) "This is the"
  77. }
  78. string(20) "e blockchain course."
  79. array(2) {
  80. [0]=>
  81. int(5410)
  82. [1]=>
  83. string(12) "This is the "
  84. }
  85. string(19) " blockchain course."
  86. array(2) {
  87. [0]=>
  88. int(5410)
  89. [1]=>
  90. string(13) "This is the b"
  91. }
  92. string(18) "blockchain course."
  93. array(2) {
  94. [0]=>
  95. int(5410)
  96. [1]=>
  97. string(14) "This is the bl"
  98. }
  99. string(17) "lockchain course."
  100. array(2) {
  101. [0]=>
  102. int(5410)
  103. [1]=>
  104. string(15) "This is the blo"
  105. }
  106. string(16) "ockchain course."
  107. array(2) {
  108. [0]=>
  109. int(5410)
  110. [1]=>
  111. string(16) "This is the bloc"
  112. }
  113. string(15) "ckchain course."
  114. array(2) {
  115. [0]=>
  116. int(5410)
  117. [1]=>
  118. string(17) "This is the block"
  119. }
  120. string(14) "kchain course."
  121. array(2) {
  122. [0]=>
  123. int(5410)
  124. [1]=>
  125. string(18) "This is the blockc"
  126. }
  127. string(13) "chain course."
  128. array(2) {
  129. [0]=>
  130. int(5410)
  131. [1]=>
  132. string(19) "This is the blockch"
  133. }
  134. string(12) "hain course."
  135. array(2) {
  136. [0]=>
  137. int(5410)
  138. [1]=>
  139. string(20) "This is the blockcha"
  140. }
  141. string(11) "ain course."
  142. array(2) {
  143. [0]=>
  144. int(5410)
  145. [1]=>
  146. string(21) "This is the blockchai"
  147. }
  148. string(10) "in course."
  149. array(2) {
  150. [0]=>
  151. int(5410)
  152. [1]=>
  153. string(22) "This is the blockchain"
  154. }
  155. string(9) "n course."
  156. array(2) {
  157. [0]=>
  158. int(5410)
  159. [1]=>
  160. string(23) "This is the blockchain "
  161. }
  162. string(8) " course."
  163. array(1) {
  164. [0]=>
  165. int(9694)
  166. }

7.2.2 php实现接收区块的有限状态机设计

php代码容易理解, 而且翻译成c比较容易. 所以先写php代码.

7.2.2.1 区块读取接收的fsm设计

  1. /* 接收区块交易的有限状态机设计:
  2. (随机数: 状态; $buffer: 字节缓存; $valence: 剩余交易数, count:交易个数; $length: 剩余读入长度)
  3. array(3786, $buffer, $length)
  4. array(1188, $buffer, $valence, $count) //接收交易个数4字节.
  5. array(3833, $buffer, $valence, $length) //接收交易.
  6. array(5176, $buffer) // 最后一个交易
  7. */

7.2.2.2 区块接收读取的代码

  1. $ cat listen.php
  2. <?php
  3. /*
  4. array(3786, $buffer, $length)
  5. array(1188, $buffer, $valence, $count)
  6. array(3833, $buffer, $valence, $length)
  7. array(5176, $buffer)
  8. create_3786();
  9. create_1188();
  10. create_3833();
  11. create_5176();
  12. */
  13. error_reporting(E_ALL);
  14. $input = file_get_contents('1.block');
  15. $situation = array(3786, '', 108);
  16. $count = 0;
  17. while (++$count) {
  18. $head = substr($input, 0, 1);
  19. $tail = substr($input, 1);
  20. echo sprintf('%d: %s -> ', $count, print_situation($situation));
  21. $situation = handle_5884($situation, ord($head));
  22. echo sprintf('%s%c', print_situation($situation), 10);
  23. if ($situation[0] == 5176)
  24. break;
  25. $input = $tail;
  26. }
  27. function print_situation($situation)
  28. {
  29. if (count($situation) == 1)
  30. return sprintf('array(%d)', $situation[0]);
  31. if (count($situation) == 2)
  32. return sprintf('array(%d, %s)', $situation[0], print_value($situation[1]));
  33. if (count($situation) == 3)
  34. return sprintf('array(%d, %s, %s)', $situation[0], print_value($situation[1]), print_value($situation[2]));
  35. if (count($situation) == 4)
  36. return sprintf('array(%d, %s, %s, %s)', $situation[0], print_value($situation[1]), print_value($situation[2]), print_value($situation[3]));
  37. }
  38. function print_value($value)
  39. {
  40. if (is_integer($value))
  41. return sprintf('%d', $value);
  42. if (is_string($value))
  43. return sprintf('string(%d)', strlen($value));
  44. }
  45. function handle_5884($situation, $byte)
  46. {
  47. if ($situation[0] == 3786) {
  48. $situation[1] = $situation[1] . chr($byte);
  49. $situation[2]--;
  50. if ($situation[2] == 0) {
  51. $valence = substr($situation[1], strlen($situation[1]) - 4);
  52. $valence = unpack('L', $valence);
  53. $valence = $valence[1];
  54. return array(1188, $situation[1], $valence, 4);
  55. }
  56. return array(3786, $situation[1], $situation[2]);
  57. }
  58. if ($situation[0] == 1188) {
  59. $situation[1] = $situation[1] . chr($byte);
  60. $situation[3]--;
  61. if ($situation[3] == 0) {
  62. $length = substr($situation[1], strlen($situation[1]) - 4);
  63. $length = unpack('L', $length);
  64. $length = $length[1];
  65. return array(3833, $situation[1], $situation[2] - 1, $length - 4);
  66. }
  67. return array(1188, $situation[1], $situation[2], $situation[3]);
  68. }
  69. if ($situation[0] == 3833) {
  70. $situation[1] = $situation[1] . chr($byte);
  71. $situation[3]--;
  72. if ($situation[2] == 0 && $situation[3] == 0)
  73. return array(5176, $situation[1]);
  74. if ($situation[3] == 0)
  75. return array(1188, $situation[1], $situation[2], 4);
  76. return array(3833, $situation[1], $situation[2], $situation[3]);
  77. }
  78. }

7.2.2.2 区块接收读取的过程展示

  1. $ php listen.php
  2. 1: array(3786, string(0), 108) -> array(3786, string(1), 107)
  3. 2: array(3786, string(1), 107) -> array(3786, string(2), 106)
  4. 3: array(3786, string(2), 106) -> array(3786, string(3), 105)
  5. 4: array(3786, string(3), 105) -> array(3786, string(4), 104)
  6. 5: array(3786, string(4), 104) -> array(3786, string(5), 103)
  7. 6: array(3786, string(5), 103) -> array(3786, string(6), 102)
  8. 7: array(3786, string(6), 102) -> array(3786, string(7), 101)
  9. 8: array(3786, string(7), 101) -> array(3786, string(8), 100)
  10. 9: array(3786, string(8), 100) -> array(3786, string(9), 99)
  11. 10: array(3786, string(9), 99) -> array(3786, string(10), 98)
  12. ...
  13. 98: array(3786, string(97), 11) -> array(3786, string(98), 10)
  14. 99: array(3786, string(98), 10) -> array(3786, string(99), 9)
  15. 100: array(3786, string(99), 9) -> array(3786, string(100), 8)
  16. 101: array(3786, string(100), 8) -> array(3786, string(101), 7)
  17. 102: array(3786, string(101), 7) -> array(3786, string(102), 6)
  18. 103: array(3786, string(102), 6) -> array(3786, string(103), 5)
  19. 104: array(3786, string(103), 5) -> array(3786, string(104), 4)
  20. 105: array(3786, string(104), 4) -> array(3786, string(105), 3)
  21. 106: array(3786, string(105), 3) -> array(3786, string(106), 2)
  22. 107: array(3786, string(106), 2) -> array(3786, string(107), 1)
  23. 108: array(3786, string(107), 1) -> array(1188, string(108), 1, 4)
  24. 109: array(1188, string(108), 1, 4) -> array(1188, string(109), 1, 3)
  25. 110: array(1188, string(109), 1, 3) -> array(1188, string(110), 1, 2)
  26. 111: array(1188, string(110), 1, 2) -> array(1188, string(111), 1, 1)
  27. 112: array(1188, string(111), 1, 1) -> array(3833, string(112), 0, 88)
  28. ...
  29. 196: array(3833, string(195), 0, 5) -> array(3833, string(196), 0, 4)
  30. 197: array(3833, string(196), 0, 4) -> array(3833, string(197), 0, 3)
  31. 198: array(3833, string(197), 0, 3) -> array(3833, string(198), 0, 2)
  32. 199: array(3833, string(198), 0, 2) -> array(3833, string(199), 0, 1)
  33. 200: array(3833, string(199), 0, 1) -> array(5176, string(200))

7.3 C语言实现接收区块

7.3.1 设计

状态机一致, 从php翻译过来, 用c语言实现.

7.3.2 程序

  1. #define TFM_DESC
  2. #include "stdio.h"
  3. #include "stdlib.h"
  4. #include "string.h"
  5. #include "sys/socket.h"
  6. #include "arpa/inet.h"
  7. #include "tfm.h"
  8. #include "tomcrypt.h"
  9. char *string_create(char *old, int length)
  10. {
  11. char *new;
  12. int *_6157;
  13. new = malloc(length + 4) + 4;
  14. memcpy(new, old, length);
  15. _6157 = (int *) (new - 4);
  16. *_6157 = length;
  17. return new;
  18. }
  19. char *string_create_improper(char *old)
  20. {
  21. char *new;
  22. int *_7193;
  23. new = malloc(strlen(old) + 4) + 4;
  24. memcpy(new, old, strlen(old));
  25. _7193 = (int *) (new - 4);
  26. *_7193 = strlen(old);
  27. return new;
  28. }
  29. char *string_create_progression(int a)
  30. {
  31. char *c;
  32. int *_3919;
  33. c = malloc(a + 4) + 4;
  34. _3919 = (int *) (c - 4);
  35. *_3919 = 0;
  36. return c;
  37. }
  38. int string_measure(char *buffer)
  39. {
  40. int *_4721;
  41. _4721 = (int *) (buffer - 4);
  42. return *_4721;
  43. }
  44. void string_update(char *object, char *buffer, int length)
  45. {
  46. int *_9492;
  47. _9492 = (int *) (object - 4);
  48. memcpy(object + *_9492, buffer, length);
  49. *_9492 += length;
  50. }
  51. void string_update_1(char *object, char quantity)
  52. {
  53. int *_7751, *_2888;
  54. _7751 = (int *) (object - 4);
  55. _2888 = (int *) (object + *_7751);
  56. *_2888 = quantity;
  57. *_7751 += 1;
  58. }
  59. void string_update_4(char *object, int quantity)
  60. {
  61. int *_7751, *_2888;
  62. _7751 = (int *) (object - 4);
  63. _2888 = (int *) (object + *_7751);
  64. *_2888 = quantity;
  65. *_7751 += 4;
  66. }
  67. void string_update_8(char *object, uint64_t quantity)
  68. {
  69. int *_7751;
  70. uint64_t *_2888;
  71. _7751 = (int *) (object - 4);
  72. _2888 = (uint64_t *) (object + *_7751);
  73. *_2888 = quantity;
  74. *_7751 += 8;
  75. }
  76. void string_update_initial(char *object, char *initial)
  77. {
  78. int *_8478, *_5970;
  79. _8478 = (int *) (object - 4);
  80. _5970 = (int *) initial;
  81. memcpy(object + *_8478, initial, *_5970);
  82. *_8478 += *_5970;
  83. }
  84. char *string_slice(char *subject, int start, int length)
  85. {
  86. return string_create(subject + start, length);
  87. }
  88. char *string_eject(char *object)
  89. {
  90. char *new;
  91. int *_6558;
  92. _6558 = (int *) (object - 4);
  93. new = malloc(*_6558);
  94. memcpy(new, object, *_6558);
  95. return new;
  96. }
  97. struct condition {
  98. int code;
  99. };
  100. struct condition_3786 {
  101. int code;
  102. char *A;
  103. int B;
  104. };
  105. struct condition_1188 {
  106. int code;
  107. char *A;
  108. int B;
  109. int C;
  110. };
  111. struct condition_3833 {
  112. int code;
  113. char *A;
  114. int B;
  115. int C;
  116. };
  117. struct condition_5176 {
  118. int code;
  119. char *A;
  120. };
  121. struct condition *create_3786(char *A, int B)
  122. {
  123. struct condition_3786 *present;
  124. present = malloc(sizeof (struct condition_3786));
  125. present->code = 3786;
  126. present->A = A;
  127. present->B = B;
  128. return (struct condition *) present;
  129. }
  130. struct condition *create_1188(char *A, int B, int C)
  131. {
  132. struct condition_1188 *present;
  133. present = malloc(sizeof (struct condition_1188));
  134. present->code = 1188;
  135. present->A = A;
  136. present->B = B;
  137. present->C = C;
  138. return (struct condition *) present;
  139. }
  140. struct condition *create_3833(char *A, int B, int C)
  141. {
  142. struct condition_3833 *present;
  143. present = malloc(sizeof (struct condition_3833));
  144. present->code = 3833;
  145. present->A = A;
  146. present->B = B;
  147. present->C = C;
  148. return (struct condition *) present;
  149. }
  150. struct condition *create_5176(char *A)
  151. {
  152. struct condition_5176 *present;
  153. present = malloc(sizeof (struct condition_5176));
  154. present->code = 5176;
  155. present->A = A;
  156. return (struct condition *) present;
  157. }
  158. struct condition *handle(struct condition *present, char byte)
  159. {
  160. int X;
  161. char *Y;
  162. struct condition_3786 *present_3786;
  163. struct condition_1188 *present_1188;
  164. struct condition_3833 *present_3833;
  165. struct condition_5176 *present_5176;
  166. if (present->code == 3786) {
  167. present_3786 = (struct condition_3786 *) present;
  168. string_update_1(present_3786->A, byte);
  169. present_3786->B--;
  170. if (present_3786->B == 0) {
  171. Y = string_slice(present_3786->A, string_measure(present_3786->A) - 4, 4);
  172. memcpy(&X, Y, 4);
  173. return create_1188(present_3786->A, X, 4);
  174. }
  175. return create_3786(present_3786->A, present_3786->B);
  176. }
  177. if (present->code == 1188) {
  178. present_1188 = (struct condition_1188 *) present;
  179. string_update_1(present_1188->A, byte);
  180. present_1188->C--;
  181. if (present_1188->C == 0) {
  182. Y = string_slice(present_1188->A, string_measure(present_1188->A) - 4, 4);
  183. memcpy(&X, Y, 4);
  184. return create_3833(present_1188->A, present_1188->B - 1, X - 4);
  185. }
  186. return create_1188(present_1188->A, present_1188->B, present_1188->C);
  187. }
  188. if (present->code == 3833) {
  189. present_3833 = (struct condition_3833 *) present;
  190. string_update_1(present_3833->A, byte);
  191. present_3833->C--;
  192. if (present_3833->B == 0 && present_3833->C == 0)
  193. return create_5176(present_3833->A);
  194. if (present_3833->C == 0)
  195. return create_1188(present_3833->A, present_3833->B, 4);
  196. return create_3833(present_3833->A, present_3833->B, present_3833->C);
  197. }
  198. }
  199. int main(int count, char **arguments)
  200. {
  201. ltc_mp = tfm_desc;
  202. register_prng(&sprng_desc);
  203. register_hash(&sha256_desc);
  204. int self, other, error, length;
  205. struct sockaddr_in address;
  206. char buffer[1000];
  207. self = socket(2, 1, 0);
  208. if (self == -1)
  209. exit(1);
  210. address.sin_family = 2;
  211. address.sin_port = htons(atoi(arguments[1]));
  212. address.sin_addr.s_addr = inet_addr("0.0.0.0");
  213. error = bind(self, (struct sockaddr *) &address, sizeof (address));
  214. if (error == -1)
  215. exit(2);
  216. error = listen(self, 1024);
  217. if (error == -1)
  218. exit(3);
  219. while(1) {
  220. other = accept(self, 0, 0);
  221. if (other == -1)
  222. exit(4);
  223. struct condition *present;
  224. present = create_3786(string_create_progression(4000000), 108);
  225. while (1) {
  226. memset(buffer, 0, 1000);
  227. length = recv(other, buffer, 1, 0);
  228. if (length == -1 || length == 0)
  229. break;
  230. present = handle(present, buffer[0]);
  231. struct condition_3786 *U;
  232. struct condition_1188 *V;
  233. struct condition_3833 *W;
  234. struct condition_5176 *M;
  235. if (present->code == 3786){
  236. U = (struct condition_3786 *) present;
  237. printf("array(%d, string(%d), %d)%c", U->code, string_measure(U->A), U->B, 10);
  238. }
  239. if (present->code == 1188){
  240. V = (struct condition_1188 *) present;
  241. printf("array(%d, string(%d), %d, %d)%c", V->code, string_measure(V->A), V->B, V->C, 10);
  242. }
  243. if (present->code == 3833){
  244. W = (struct condition_3833 *) present;
  245. printf("array(%d, string(%d), %d, %d)%c", W->code, string_measure(W->A), W->B, W->C, 10);
  246. }
  247. if (present->code == 5176){
  248. M = (struct condition_5176 *) present;
  249. printf("array(%d, string(%d))%c", M->code, string_measure(M->A), 10);
  250. }
  251. if (present->code == 5176) {
  252. close(other);
  253. break;
  254. }
  255. }
  256. }
  257. }

7.3.3 运行结果

用nc传送字节, listen程序接收.

7.3.3.1 第一个区块接收

  1. cat 1.block | nc 127.0.0.1 6002
  1. tcc -c listen.c -o listen.o && tcc listen.o ../libtomcrypt.a ../libtfm.a -o listen
  2. ./listen 6002
  3. array(3786, string(1), 107)
  4. array(3786, string(2), 106)
  5. array(3786, string(3), 105)
  6. .....
  7. array(3786, string(98), 10)
  8. array(3786, string(99), 9)
  9. array(3786, string(100), 8)
  10. array(3786, string(101), 7)
  11. array(3786, string(102), 6)
  12. array(3786, string(103), 5)
  13. array(3786, string(104), 4)
  14. array(3786, string(105), 3)
  15. array(3786, string(106), 2)
  16. array(3786, string(107), 1)
  17. array(1188, string(108), 1, 4)
  18. array(1188, string(109), 1, 3)
  19. array(1188, string(110), 1, 2)
  20. array(1188, string(111), 1, 1)
  21. array(3833, string(112), 0, 88)
  22. array(3833, string(113), 0, 87)
  23. array(3833, string(114), 0, 86)
  24. ...
  25. array(3833, string(190), 0, 10)
  26. array(3833, string(191), 0, 9)
  27. array(3833, string(192), 0, 8)
  28. array(3833, string(193), 0, 7)
  29. array(3833, string(194), 0, 6)
  30. array(3833, string(195), 0, 5)
  31. array(3833, string(196), 0, 4)
  32. array(3833, string(197), 0, 3)
  33. array(3833, string(198), 0, 2)
  34. array(3833, string(199), 0, 1)
  35. array(5176, string(200))

7.3.3.2 第二个区块接收

  1. cat 2.block | nc 127.0.0.1 6002
  1. array(3786, string(1), 107)
  2. array(3786, string(2), 106)
  3. array(3786, string(3), 105)
  4. ....
  5. array(3786, string(98), 10)
  6. array(3786, string(99), 9)
  7. array(3786, string(100), 8)
  8. array(3786, string(101), 7)
  9. array(3786, string(102), 6)
  10. array(3786, string(103), 5)
  11. array(3786, string(104), 4)
  12. array(3786, string(105), 3)
  13. array(3786, string(106), 2)
  14. array(3786, string(107), 1)
  15. array(1188, string(108), 2, 4)
  16. array(1188, string(109), 2, 3)
  17. array(1188, string(110), 2, 2)
  18. array(1188, string(111), 2, 1)
  19. array(3833, string(112), 1, 88)
  20. array(3833, string(113), 1, 87)
  21. array(3833, string(114), 1, 86)
  22. ...
  23. array(3833, string(190), 1, 10)
  24. array(3833, string(191), 1, 9)
  25. array(3833, string(192), 1, 8)
  26. array(3833, string(193), 1, 7)
  27. array(3833, string(194), 1, 6)
  28. array(3833, string(195), 1, 5)
  29. array(3833, string(196), 1, 4)
  30. array(3833, string(197), 1, 3)
  31. array(3833, string(198), 1, 2)
  32. array(3833, string(199), 1, 1)
  33. array(1188, string(200), 1, 4)
  34. array(1188, string(201), 1, 3)
  35. array(1188, string(202), 1, 2)
  36. array(1188, string(203), 1, 1)
  37. array(3833, string(204), 0, 269)
  38. array(3833, string(205), 0, 268)
  39. array(3833, string(206), 0, 267)
  40. array(3833, string(207), 0, 266)
  41. ...
  42. array(3833, string(462), 0, 11)
  43. array(3833, string(463), 0, 10)
  44. array(3833, string(464), 0, 9)
  45. array(3833, string(465), 0, 8)
  46. array(3833, string(466), 0, 7)
  47. array(3833, string(467), 0, 6)
  48. array(3833, string(468), 0, 5)
  49. array(3833, string(469), 0, 4)
  50. array(3833, string(470), 0, 3)
  51. array(3833, string(471), 0, 2)
  52. array(3833, string(472), 0, 1)
  53. array(5176, string(473))

7.4 接收并存储区块初步实现及处理函数定义

通过socket接收, 然后存储到storage,然后断开连接.(先不实现多线程)
函数分2类:
纯函数, 与system call无关,单纯计算,例如字符串处理.
不纯函数其他函数调用了system call. 与时间,文件,端口有关.

main -> audit -> handle -> 调用其他的函数实现插件如钱包等.

7.4.1 处理函数规划

handle() ---> following:
SubmitBlock =6696 handle_6696
GetBalance = 1548 handle_1548
GetInformation handle_8906
Send = 4097 handle_4097 交易是不是成功的.
GetWork = 8605 handle_8605
SubmitWork = 3905 handle_3905
SubmitTransaction = 8783
GetPeers= 1907
Ping= 8285

  1. #define GETBLOCKS _____
  2. _____
  3. _____

7.4.2 区块接收程序

  1. //解析输入参数, 存储,私钥,端口
  2. // ./ccn -c $FOLDER -k $KEY -p $PORT
  3. // 为了灵活,也可以使用状态机来分析参数.
  4. struct arguments *parse_arguments(int count, char **source)
  5. {
  6. struct arguments *arguments;
  7. if (count != 4)
  8. return 0;
  9. arguments = malloc(sizeof (struct arguments));
  10. arguments->conservation = source[2];
  11. arguments->key = source[4];
  12. arguments->port = atoi(source[6]);
  13. return arguments;
  14. }
  15. struct condition *handle(struct condition *present, char byte)
  16. {
  17. int X;
  18. char *Y;
  19. struct condition_3786 *present_3786;
  20. struct condition_1188 *present_1188;
  21. struct condition_3833 *present_3833;
  22. struct condition_5176 *present_5176;
  23. if (present->code == 3786) {
  24. present_3786 = (struct condition_3786 *) present;
  25. string_update_1(present_3786->A, byte);
  26. present_3786->B--;
  27. if (present_3786->B == 0) {
  28. Y = string_slice(present_3786->A, string_measure(present_3786->A) - 4, 4);
  29. memcpy(&X, Y, 4);
  30. return create_1188(present_3786->A, X, 4);
  31. }
  32. return create_3786(present_3786->A, present_3786->B);
  33. }
  34. if (present->code == 1188) {
  35. present_1188 = (struct condition_1188 *) present;
  36. string_update_1(present_1188->A, byte);
  37. present_1188->C--;
  38. if (present_1188->C == 0) {
  39. Y = string_slice(present_1188->A, string_measure(present_1188->A) - 4, 4);
  40. memcpy(&X, Y, 4);
  41. return create_3833(present_1188->A, present_1188->B - 1, X - 4);
  42. }
  43. return create_1188(present_1188->A, present_1188->B, present_1188->C);
  44. }
  45. if (present->code == 3833) {
  46. present_3833 = (struct condition_3833 *) present;
  47. string_update_1(present_3833->A, byte);
  48. present_3833->C--;
  49. if (present_3833->B == 0 && present_3833->C == 0)
  50. return create_5176(present_3833->A);
  51. if (present_3833->C == 0)
  52. return create_1188(present_3833->A, present_3833->B, 4);
  53. return create_3833(present_3833->A, present_3833->B, present_3833->C);
  54. }
  55. }
  56. void audit(int port, char *private, char *storage)
  57. {
  58. int self, other, error, length;
  59. struct sockaddr_in address;
  60. char buffer[1000];
  61. struct condition *present;
  62. struct condition_5176 *_1126;
  63. self = socket(2, 1, 0);
  64. if (self == -1)
  65. exit(57);
  66. address.sin_family = 2;
  67. address.sin_port = htons(port);
  68. address.sin_addr.s_addr = inet_addr("0.0.0.0");
  69. error = bind(self, (struct sockaddr *) &address, sizeof (address));
  70. if (error == -1)
  71. exit(51);
  72. error = listen(self, 1024);
  73. if (error == -1)
  74. exit(22);
  75. while(1) {
  76. other = accept(self, 0, 0);
  77. if (other == -1)
  78. exit(4);
  79. present = create_3786(string_create_progression(1000000), 108);
  80. while (1) {
  81. memset(buffer, 0, 1000);
  82. length = recv(other, buffer, 1, 0);
  83. if (length == -1 || length == 0)
  84. break;
  85. present = handle(present, buffer[0]);
  86. if (present->code == 5176) {
  87. _1126 = (struct condition_5176 *) present;
  88. storage_add(storage, get_sha256(_1126->A, 108), _1126->A, string_measure(_1126->A));
  89. printf("count: %d%c", storage_count(storage), 10);
  90. close(other);
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. // 8906 GetInformation
  97. int main(int _1480, char **_2130)
  98. {
  99. ltc_mp = tfm_desc;
  100. register_prng(&sprng_desc);
  101. register_hash(&sha256_desc);
  102. char *storage, *_3541, *private;
  103. int _5999;
  104. struct arguments *arguments;
  105. arguments = parse_arguments(_1480, _2130);
  106. if (arguments == 0)
  107. exit(47);
  108. storage = storage_create(400, "", arguments->conservation);
  109. _3541 = read_file(arguments->key, &_5999);
  110. private = string_create(_3541, _5999);
  111. audit(arguments->port, private, storage);
  112. }

7.4.3 接收区块命令行调用

./ccn -c /tmp/blocks -k yuanxun.private -p 7000

7.4.4 接受程序

7.4.4 节点网络监听的规则说明

监听的规则: ?? 16节课. 16:00
程序监听一个端口, 接收区块. 如果其他人需要时也能发送.
不仅用户和监听节点之间发可以发送区块.
节点之间也可以自动化地发送区块.
例如约定每几分钟或小时要与哪些节点进行沟通, 联系不上时再尝试3次.
每次在定时区间内,要问其他节点的状态, 还有认识的节点数量如果少于6个,要增加到朋友列表,维持新的节点到列表中.
这样就构成了节点网络.

7.4.5 发钱收钱原理

BTC模式也是我们设计实现的模式.
节点载入私钥. 当用户要确定发钱时, 节点用私钥搜索所有的数据库, 找到个人的一部分钱的碎片, 作为input来发送.
通过handle呼叫更多函数,来实现钱包等功能.

7.5 对所有公共函数进行分类.

7.5.1 跟文串相关的函数

string_create/2
string_create_improper/1
string_create_progression/1
string_eject/1
string_measure/1
string_update/3
string_update_1/2
string_update_4/2
string_update_8/2
string_update_initial/2

7.5.2 跟加密相关的函数

get_md5/2
get_private/1
get_public/2
get_sha256/2
sign/2
verify/2

7.5.3 混杂的函数

get_maximal/0
get_minimal/0
print_digest/1
read_file/2
render_digest/1
scan/1
write_file/2

7.5.4 跟区链有直接关系的函数

build_input/4
build_output/2
get_merkle_root/2
validate_offsets/2
validate_offsets_input/2
validate_offsets_output/2
validate_offsets_transaction/2

8. 侧链设计原理

需要个小的智能合约. 需要锁住1条链上的钱.
要做侧链,
结构要从 address, amount.改为
address不止是地址,还要包括虚拟机之类的东西.

我们提议让父链和侧链相互做数据的SPV验证。由于不能指望父链客户端能看到每条侧链,为了证明所有权,用户必须从侧链导入工作量的证明到父链。在对称式双向楔入中,反向的操作也是如此。

为了让比特币系统成为父链,需要有一个能识别和验证SPV证明的脚本扩展。最起码的要求是,这种证明需要做得足够小,以便能放进比特币系统一个交易之中。不过,这只是一个软分叉,对于不使用新功能的交易不会产生影响。

BTC 可以有无限多的侧链.

identity = digest (摘要)
digest 来自 head ( current, nounce,...)
current <--- body (merkle tree)

某个交易存在在连上.
有2个方式确认.
1. 拥有整个区块链. 每个区块和身份

9. 侧链开发

10. 智能合约设计原理

10.1 virtual machine & script

智能合约是由指令来组成的. 指令是通过虚拟机来执行的.
虚拟机分2种.

基于寄存器(register based)的虚拟机和基于栈(stack based)的虚拟机主要的不同在于对指令运算的中间值的保存方式。这些中间值包括各种运算的结果值,传给各个指令的参数等等。前者一般会设置几个寄存器,如累加寄存器;后者则没有寄存器,只有一个用来保存这些值的栈。

Stack based 虚拟机图示:
image_1bv0veevacgg1q7evjm89nsjd9.png-107.8kB
栈虚拟机主要包括以上三部分:虚拟机、指令集、外部接口。
其中虚拟机内部构造主要是数据、指令、堆栈三部分,指令对数据进行操作,将数据装载进堆栈中以备运算和处理。

基于栈的举例展示栈的变化:
image_1bv11h6587ej161g1kq11v1pto9m.png-7.4kB
基于栈的举例包括指令:
image_1bv11vlmbt1i1sqg1km41ccm133g1j.png-78.5kB

基于寄存器的举例图示:
image_1bv128ju11hvbsq6ac210cj1qkk2d.png-48.8kB

循环代码翻译成Stack based machine的语言

一段循环代码

  1. $i = 0; while($i <5 ) { $i++; }
  2. ==>
  3. lable 1000 dup push 5 GT jmpz 2000 push 1 add jump 1000 lable 2000

跳跃点与跳跃示意:

  1. $i = 0;
  2. while label 1000
  3. ($i <5 ) jmpz 2000 (有条件跳)
  4. {
  5. $i++
  6. ; jump 1000
  7. }
  8. lable 2000

循环代码翻译过程解释

  1. $i = 0; ==> push 0
  2. 对于while循环, 分成条件和内容2部分, 也就有2个跳跃的地点
  3. 跳跃的地点: while ... ===> lable 1000
  4. 因为每次操作会吃掉一个数, 需要把i复制 $i ==> dup
  5. 因为栈最上面与次上比较,反过来, 所以改为大于GT: < 5 ==> push 5 GT
  6. 然后有条件跳跃: ) ==> jmpz 2000
  7. i=i+1 : $i ++ ==> push 1 add
  8. ; ==> jump 1000
  9. } lable 2000
  10. 循环里可以嵌套发钱的函数:
  11. send(addr, money);
  12. 发钱: push 10 push 2535624466 send

Fibbonacci

  1. $a =1; $b = 1; while(1) { $c = $a + $b; print($c); $a = $b; $b = $c; }
  2. ==>
  3. push 1 push 1 lable 1000
  4. dup swap2 dup // A B; A B B; B B A; B B A A;
  5. swap3 // A B A B;
  6. add dup print // A B C C;
  7. jump 1000

另一种简洁实现fibbonacci:
PUSH 1 PUSH 1 LABEL 1 DUP SWAP2 ADD JMP 1

  1. a =500;
  2. b= 7;
  3. c=0;
  4. while(c<=500)
  5. {
  6. if(c % 7 == 0)
  7. echo (c);
  8. c++;
  9. }
  10. push 500;
  11. push 7
  12. push 0
  13. dup
  14. push 500

10.2 比特币 Bitcoin

Bitcoin uses a scripting system for transactions. Forth-like, Script is simple, stack-based, and processed from left to right. It is purposefully not Turing-complete, with no loops.
A script is essentially a list of instructions recorded with each transaction that describe how the next person wanting to spend the Bitcoins being transferred can gain access to them. The script for a typical Bitcoin transfer to destination Bitcoin address D simply encumbers future spending of the bitcoins with two things: the spender must provide
- 1. a public key that, when hashed, yields destination address D embedded in the script, and
- 2. a signature to show evidence of the private key corresponding to the public key just provided.
Scripting provides the flexibility to change the parameters of whats needed to spend transferred Bitcoins. For example, the scripting system could be used to require two private keys, or a combination of several, or even no keys at all.

脚本本质上是每个交易记录的指令列表,描述下一个想要花费比特币的人如何能够访问他们。一个典型的比特币转移到目的地的脚本比特币地址D简单地加载比特币的未来支出有两件事情:花费者必须提供
1. 一个公钥,当散列时,产生嵌入在脚本中的目标地址D
2. 一个签名显示与刚刚提供的公钥对应的私钥的证据。
脚本提供了更改传输比特币所需花费参数的灵活性。例如,脚本系统可以用来需要两个私人密钥,或几个,甚至没有任何密钥的组合。

BTC 起初想法有很多没有落实. 本来也有智能合约系统, 但不是图灵完备的.
智能合约系统不是按照账号,而是按照碎片设置智能合约. 后来因为引起安全漏洞,一部分关闭了. 还存在,但是有限制, 如果不符合2,3个模板的话,交易就会被拒绝.
而ETH保证了用户能创造图灵完备的合约.

我们设计的output里是address,amount. BTC还包括一个智能合约, 实现了数个模板功能:
1 Standard Transaction to Bitcoin address (pay-to-pubkey-hash)
2 Obsolete pay-to-pubkey transaction
3 Provably Unspendable/Prunable Outputs (钱锁定)
4 Anyone-Can-Spend Outputs (任何人都能花这笔钱)
5 Transaction puzzle (密码符合就可以得到钱)

其中1里的scriptPubKey相当于我们Output里的一个属性, 地址.
scriptSig, 是相当于input的一个属性,相当我们公钥,签名.
我们的地址是对公钥作md5. BTC采用的是个不同的算法.

CoinJoin
用来把钱混在一起, 区分不出来谁的钱
image_1buvuo75f1ie51qbf9d21dulhf09.png-40.2kB

10.3 以太坊 Ethereum

2016年以太坊遭到攻击
白皮书内容不多, wiki更新不多.
复杂些的要自己去发现.

区块特点

每17秒出现一个区块, 奖励不止给最快的人, 也发给其他挖区块的人. 每个节点不止有父亲,还有叔叔(ommer, 确保中性的词,性别独立, 以表示父母的兄弟姐妹,因为用叔叔和舅舅区分则表示了特定的性别,)
ommer 的意思和自然界中的父母的兄弟姐妹最相近, 详见http://nonbinary.org/wiki/Gender_neutral_language#Family_Terms

为了防止矿池大蒜粒, 运行之前付钱, 钱数不定.
为了避免网络滥用及回避由于图灵完整性而带来的一些
不可避免的问题,在以太坊中所有的程序执行都需要费用。
各种操作费用以gas (详见附录G ) 为单位计算。任意的程
序片段(包括合约创建、信息调回、利用及访问账户存储、
在虚拟机上执行操作等)都可以根据规则计算出消耗的燃
料数量。
运行越复杂, 需要的gas越多.

智能合约不会自己执行, 需要有人支付费用,呼叫它才能执行.

创造地址时,需要随机数字的, 如果知道了你的随机数字, 就有可能知道你
eth创造地址时也需要钱.

Message Call就是发送钱. 额度
智能合约和地址是一对一的形式.

EVM 是32字节, 256bit.
我们创造的是4字节.

执行模型具体说明怎么使用一系列字节代码指令和一个
小的环境数据元组去改变这个系统状态。这些是通过以太
坊虚拟机(Ethereum Virtual Machine - EVM), 这个虚拟
状态机来实现的。它是一个准图灵机, 说“准”是因为计算
会被燃料所限制。
9.1. 基础. EVM 基于栈结构, 机器的字大小(以及栈中数
据的大小)是256 位。主要是便于执行Keccak-256 位哈希
及椭圆曲线计算。内存模型基于字寻址的字节数据。栈的最
大深度为1024。EVM 也有一个独立的存储模型;类似内
存但更像一个字节数组, 一个基于字寻址的字数组。不像易
变的内存,存储是非易变的且是作为系统状态的一部分被
维护。所有内存和存储中的数据会初始化为0。
EVM 不是标准的诺依曼结构。它通过一个特别的指令
把程序代码保存在一个虚拟的可以交互的ROM 中, 而不是
保存在一般性可访问的内存或存储中。

对于一个账户的执行,内存总费用和需要的32 字节最
小倍数的内存量成正比, 即存1个字节也要32字节的费用.

ETH没有挖矿机

比特币世界中一个灾难是ASICs。有一些计算硬件仅仅
是为了做一个简单的任务而存在。在比特币的案例中,这个
任务就是SHA256 哈希函数。当ASICs 为了工作量证明函
数而存在时,两个的目标都会变得危险。因此,一个可抵抗
ASIC 的工作量证明函数(比如难以在专用硬件上执行, 或
者在专用硬件执行时并不划算)可以作为众所周知的银弹。
防止ASIC 漏洞的两个方向:第一是去让它变成有序列
的内存困难,比如:设计一个函数, 确定随机数需要大量的
内存和带宽, 以至于这些内存不能被并行地去计算随机数。
第二个方向是让计算变得更普遍化; 对于这个普遍化的计
算, 使得特殊硬件和普通的桌面计算机计算起来都差不多。

有越多的机器加入,带宽越慢.(把整个世界看成1个机器,带宽有限)

EVM的每一步都是要付费的.
eos 号称效率比ETH高几十万倍.

智能合约的开发工具还不完善. 目前的都是在核心团队的指导下完成的.
这个技术在很早就存在的.

10.4 仿照以太坊EVM扩充实现为32字节

仿照以太坊, 以黄皮书的技术规范进行设计. 我们设计的支持4字节的php代码就要扩充.

  1. PUSH5 "hello"
  2. [0, 0, 0, 0, ..., h, e, l, l, o]
  3. PUSH32 0, 0, 0, ... "hello"
  4. [0, 0, 0, 0, ..., h, e, l, l, o]

11. 智能合约开发

11.1 虚拟机的php实现设计与原型代码

智能合约是由指令来组成的. 先看下我们设计的基本指令集:

  1. +-*/%
  2. and, or, xor, not
  3. < > = != = >=
  4. ADD, SUB, MUL, DIV, MOD
  5. AND, OR, XOR, NOT
  6. LT, GT, EQ, NE, LEQ, GEQ
  7. ADD, SUB, MUL, DIV, MOD (INTEGER,INTEGER) -> INTEGER
  8. AND, OR ,XOR (INTEGER, INTEGER) -> BINARY
  9. LT,GT,EQ,NE,LEQ,GEQ (INTEGER,INTEGER) -> BINARY
  10. NOT (BINARY) -> BINARY

register machine
stack machine
(integer, integer) -> integer
(binary, binary) -> binary
binary -> binary

指令程序举例说明:
image_1bv1q6hcu4ipkio1faa1a3i1rt9.png-669.9kB

  1. /* stack machine:
  2. JMP -- 无条件的跳
  3. JMPZ -- 有条件的跳 - 要是堆栈最上面是0
  4. DUP
  5. LT - 少于
  6. LTE - 少于或者等于
  7. EQ - 等于
  8. GT - 多于
  9. GTE - 多于或者等于
  10. LABEL - 控制地点, 即位置
  11. while() if()
  12. $i = 0;
  13. .1000 while ($i < 5) { $i++; } .2000
  14. PUSH 0 LABEL 1000 DUP PUSH 5 GT JMPZ 2000 PUSH 1 ADD JUMP 1000 POP
  15. */

智能合约的代码:

  1. <?php
  2. // execute(sprintf('PUSH %d PUSH %d HALT SEND', rand(), rand(1, 10)));
  3. // $i = 0; while($i < 5) { $i++; }
  4. // $a = 1; $b = 1; while(1) { $c = $a + $b; print($c); $a = $b; $b = $c;
  5. // PUSH 1 PUSH 1 LABEL 1000
  6. // DUP SWAP2 DUP SWAP3 ADD DUP PRINT
  7. // DUP PUSH 10 SWAP1 MOD PUSH 0 EQ JMP 2000
  8. // SWAP1 SWAP2 POP
  9. // JMP 1000
  10. // LABEL 2000
  11. // PUSH 1 PUSH 1 LABEL 1000 DUP SWAP2 DUP SWAP3 ADD DUP PRINT DUP PUSH 10 SWAP1 MOD PUSH 0 NEQ JMPZ 2000 SWAP1 SWAP2 POP JMP 1000 LABEL 2000
  12. // execute(sprintf('PUSH 0 LABEL 1000 DUP PUSH 5 GT JMPZ 2000 PUSH 1 ADD PUSH %d PUSH %d SEND JMP 1000 LABEL 2000', rand(), rand()));
  13. execute('PUSH 1 PUSH 1 LABEL 1000 DUP SWAP2 DUP SWAP3 ADD DUP PRINT DUP PUSH 10 SWAP1 MOD PUSH 0 NE JMPZ 2000 SWAP1 SWAP2 POP JMP 1000 LABEL 2000');
  14. // $_0000 = convert('PUSH 3 PUSH 4 LABEL 2000 POP POP JMP 2000 JMPZ 2000');
  15. //var_dump($_0000);
  16. /*
  17. ADD, SUB, MUL, DIV, MOD
  18. AND, OR, XOR, NOT
  19. LT, GT, EQ, NE, LEQ, GEQ
  20. + - * / %
  21. and, or, xor, not
  22. < > = != <= >=
  23. JMP -- wutiaojian de tiao
  24. JMPZ -- youtiaojian de tiao - yaoshi duizhan zuishangmian shi ling
  25. DUP
  26. LT - shaoyu
  27. LTE - shaoyu huozhe dengyu
  28. EQ - dengyu
  29. GT - duoyu
  30. GTE - duoyu huozhe dengyu
  31. LABEL - kongzhi didian
  32. while() if()
  33. $i = 0;
  34. .1000 while ($i < 5) { $i++; } .2000
  35. PUSH 0 LABEL 1000 DUP PUSH 5 GT JMPZ 2000 PUSH 1 ADD JUMP 1000 POP
  36. */
  37. function convert($string) {
  38. $operations = array();
  39. $_0000 = explode(' ', $string);
  40. $pieces = array();
  41. foreach ($_0000 as $_0001) {
  42. $_0001 = trim($_0001);
  43. if (strlen($_0001) > 0)
  44. { $pieces[] = $_0001; }
  45. }
  46. $index = 0;
  47. while ($index < count($pieces)) {
  48. if ($pieces[$index] == 'PUSH' || $pieces[$index] == 'LABEL' || $pieces[$index] == 'JMP' || $pieces[$index] == 'JMPZ') {
  49. $operations[] = array($pieces[$index], $pieces[$index + 1]);
  50. $index += 2;
  51. continue;
  52. }
  53. $operations[] = array($pieces[$index]);
  54. $index++;
  55. }
  56. return $operations;
  57. }
  58. /*
  59. shallow storage - byte array array()
  60. deep storage - byte array array()
  61. stack - four bytes array()
  62. instruction pointer
  63. ADD SUB MUL DIV MOD
  64. DONGCI: add, subtract, multiply, divide, modulate
  65. MINGCI: addition, subtraction, multiplication, division, modulation
  66. AND OR NOT XOR
  67. READ, WRITE
  68. LOAD, STORE
  69. array_pop, array_push
  70. function: string -> string
  71. 3 + 5
  72. array_push 3 array_push 5 ADD
  73. array_push 3
  74. array_push 5
  75. ADD
  76. array_push 3 array(3)
  77. array_push 5 array(3, 5)
  78. ADD array(8)
  79. */
  80. function render($stack) {
  81. $_0000 = '';
  82. foreach ($stack as $_0001) {
  83. $_0000 = sprintf('%s, %d', $_0000, $_0001);
  84. }
  85. return substr($_0000, 2);
  86. }
  87. function execute($string) {
  88. execute_0984(convert($string));
  89. }
  90. function execute_0984($operations) {
  91. $stack = array();
  92. echo sprintf('stack: %s%c', render($stack), 10);
  93. $index = 0;
  94. $length = count($operations);
  95. while($index < $length) {
  96. $_0000 = $operations[$index];
  97. echo sprintf('-- %s %s%c', $_0000[0], isset($_0000[1])? strval($_0000[1]): '', 10);
  98. $bundle = step($stack, $_0000);
  99. if ($bundle[0] == 0) {
  100. echo sprintf('stack: %s%c', render($bundle[1]), 10);
  101. $stack = $bundle[1];
  102. $index++;
  103. continue;
  104. }
  105. if ($bundle[0] == 1) {
  106. echo sprintf('-- SPECIAL EVENT: HALTED!! DIED!!%c', 10);
  107. break;
  108. }
  109. if ($bundle[0] == 2) {
  110. echo sprintf('stack: %s%c', render($bundle[2]), 10);
  111. $stack = $bundle[2];
  112. $index = find($operations, $bundle[1]);
  113. if ($index == -1)
  114. { die('INVALID ADDRESS!!'); }
  115. continue;
  116. }
  117. }
  118. }
  119. function find($operations, $label) {
  120. $index = 0;
  121. while ($index < count($operations)) {
  122. if ($operations[$index][0] != 'LABEL')
  123. { $index++; continue; }
  124. if ($operations[$index][34] == $label)
  125. { return $index; }
  126. $index++;
  127. }
  128. return -1;
  129. }
  130. function step($stack, $operation) {
  131. if ($operation[0] == 'JMP') {
  132. return array(2, $operation[1], $stack);
  133. }
  134. if ($operation[0] == 'JMPZ') {
  135. $a = array_pop($stack);
  136. if ($a == 0)
  137. { return array(2, $operation[1], $stack); }
  138. return array(0, $stack);
  139. }
  140. if ($operation[0] == 'LABEL') {
  141. return array(0, $stack);
  142. }
  143. if ($operation[0] == 'SWAP1') {
  144. $a = array_pop($stack);
  145. $b = array_pop($stack);
  146. array_push($stack, $a);
  147. array_push($stack, $b);
  148. return array(0, $stack);
  149. }
  150. if ($operation[0] == 'SWAP2') {
  151. $a = array_pop($stack);
  152. $b = array_pop($stack);
  153. $c = array_pop($stack);
  154. array_push($stack, $a);
  155. array_push($stack, $b);
  156. array_push($stack, $c);
  157. return array(0, $stack);
  158. }
  159. if ($operation[0] == 'SWAP3') {
  160. $a = array_pop($stack);
  161. $b = array_pop($stack);
  162. $c = array_pop($stack);
  163. $d = array_pop($stack);
  164. array_push($stack, $a);
  165. array_push($stack, $c);
  166. array_push($stack, $b);
  167. array_push($stack, $d);
  168. return array(0, $stack);
  169. }
  170. if ($operation[0] == 'ADD') {
  171. $a = array_pop($stack);
  172. $b = array_pop($stack);
  173. array_push($stack, $a + $b);
  174. return array(0, $stack);
  175. }
  176. if ($operation[0] == 'SUB') {
  177. $a = array_pop($stack);
  178. $b = array_pop($stack);
  179. array_push($stack, $a - $b);
  180. return array(0, $stack);
  181. }
  182. if ($operation[0] == 'MUL') {
  183. $a = array_pop($stack);
  184. $b = array_pop($stack);
  185. array_push($stack, $a * $b);
  186. return array(0, $stack);
  187. }
  188. if ($operation[0] == 'DIV') {
  189. $a = array_pop($stack);
  190. $b = array_pop($stack);
  191. array_push($stack, floor($a / $b));
  192. return array(0, $stack);
  193. }
  194. if ($operation[0] == 'MOD') {
  195. $a = array_pop($stack);
  196. $b = array_pop($stack);
  197. array_push($stack, $a % $b);
  198. return array(0, $stack);
  199. }
  200. if ($operation[0] == 'AND') {
  201. $a = array_pop($stack);
  202. $b = array_pop($stack);
  203. array_push($stack, boolval($a) && boolval($b)? 1: 0);
  204. return array(0, $stack);
  205. }
  206. if ($operation[0] == 'OR') {
  207. $a = array_pop($stack);
  208. $b = array_pop($stack);
  209. array_push($stack, boolval($a) || boolval($b)? 1: 0);
  210. return array(0, $stack);
  211. }
  212. if ($operation[0] == 'XOR') {
  213. $a = array_pop($stack);
  214. $b = array_pop($stack);
  215. array_push($stack, (boolval($a) && ! boolval($b)) || (! boolval($a) && boolval($b))? 1: 0);
  216. return array(0, $stack);
  217. }
  218. if ($operation[0] == 'NOT') {
  219. $a = array_pop($stack);
  220. array_push($stack, boolval($a)? 0: 1);
  221. return array(0, $stack);
  222. }
  223. if ($operation[0] == 'PUSH') {
  224. array_push($stack, $operation[1]);
  225. return array(0, $stack);
  226. }
  227. if ($operation[0] == 'POP') {
  228. array_pop($stack);
  229. return array(0, $stack);
  230. }
  231. if ($operation[0] == 'SEND') {
  232. $a = array_pop($stack);
  233. $b = array_pop($stack);
  234. echo sprintf('++ SPECIAL EVENT: %d was sent to %d%c', $a, $b, 10);
  235. return array(0, $stack);
  236. }
  237. if ($operation[0] == 'PRINT') {
  238. $a = array_pop($stack);
  239. echo sprintf('%c[32m++ PRINT: %d%c[0m%c', 27, $a, 27, 10);
  240. return array(0, $stack);
  241. }
  242. if ($operation[0] == 'HALT') {
  243. return array(1);
  244. }
  245. if ($operation[0] == 'DUP') {
  246. $a = array_pop($stack);
  247. array_push($stack, $a);
  248. array_push($stack, $a);
  249. return array(0, $stack);
  250. }
  251. if ($operation[0] == 'LT') {
  252. $a = array_pop($stack);
  253. $b = array_pop($stack);
  254. array_push($stack, $a < $b? 1: 0);
  255. return array(0, $stack);
  256. }
  257. if ($operation[0] == 'LTE') {
  258. $a = array_pop($stack);
  259. $b = array_pop($stack);
  260. array_push($stack, $a <= $b? 1: 0);
  261. return array(0, $stack);
  262. }
  263. if ($operation[0] == 'EQ') {
  264. $a = array_pop($stack);
  265. $b = array_pop($stack);
  266. array_push($stack, $a == $b? 1: 0);
  267. return array(0, $stack);
  268. }
  269. if ($operation[0] == 'NE') {
  270. $a = array_pop($stack);
  271. $b = array_pop($stack);
  272. array_push($stack, $a != $b? 1: 0);
  273. return array(0, $stack);
  274. }
  275. if ($operation[0] == 'GT') {
  276. $a = array_pop($stack);
  277. $b = array_pop($stack);
  278. array_push($stack, $a > $b? 1: 0);
  279. return array(0, $stack);
  280. }
  281. if ($operation[0] == 'GTE') {
  282. $a = array_pop($stack);
  283. $b = array_pop($stack);
  284. array_push($stack, $a >= $b? 1: 0);
  285. return array(0, $stack);
  286. }
  287. }

运行结果:

  1. stack:
  2. -- PUSH 1
  3. stack: 1
  4. -- PUSH 1
  5. stack: 1, 1
  6. -- LABEL 1000
  7. stack: 1, 1
  8. -- DUP
  9. stack: 1, 1, 1
  10. -- SWAP2
  11. stack: 1, 1, 1
  12. -- DUP
  13. stack: 1, 1, 1, 1
  14. -- SWAP3
  15. stack: 1, 1, 1, 1
  16. -- ADD
  17. stack: 1, 1, 2
  18. -- DUP
  19. stack: 1, 1, 2, 2
  20. -- PRINT
  21. ++ PRINT: 2
  22. stack: 1, 1, 2
  23. -- DUP
  24. stack: 1, 1, 2, 2
  25. -- PUSH 10
  26. stack: 1, 1, 2, 2, 10
  27. -- SWAP1
  28. stack: 1, 1, 2, 10, 2
  29. -- MOD
  30. stack: 1, 1, 2, 2
  31. -- PUSH 0
  32. stack: 1, 1, 2, 2, 0
  33. -- NE
  34. stack: 1, 1, 2, 1
  35. -- JMPZ 2000
  36. stack: 1, 1, 2
  37. -- SWAP1
  38. stack: 1, 2, 1
  39. -- SWAP2
  40. stack: 1, 2, 1
  41. -- POP
  42. stack: 1, 2
  43. -- JMP 1000
  44. stack: 1, 2
  45. -- LABEL 1000
  46. stack: 1, 2
  47. -- DUP
  48. stack: 1, 2, 2
  49. -- SWAP2
  50. stack: 2, 2, 1
  51. -- DUP
  52. stack: 2, 2, 1, 1
  53. -- SWAP3
  54. stack: 1, 2, 1, 2
  55. -- ADD
  56. stack: 1, 2, 3
  57. -- DUP
  58. stack: 1, 2, 3, 3
  59. -- PRINT
  60. ++ PRINT: 3
  61. stack: 1, 2, 3
  62. -- DUP
  63. stack: 1, 2, 3, 3
  64. -- PUSH 10
  65. stack: 1, 2, 3, 3, 10
  66. -- SWAP1
  67. stack: 1, 2, 3, 10, 3
  68. -- MOD
  69. stack: 1, 2, 3, 3
  70. -- PUSH 0
  71. stack: 1, 2, 3, 3, 0
  72. -- NE
  73. stack: 1, 2, 3, 1
  74. -- JMPZ 2000
  75. stack: 1, 2, 3
  76. -- SWAP1
  77. stack: 1, 3, 2
  78. -- SWAP2
  79. stack: 2, 3, 1
  80. -- POP
  81. stack: 2, 3
  82. -- JMP 1000
  83. stack: 2, 3
  84. -- LABEL 1000
  85. stack: 2, 3
  86. -- DUP
  87. stack: 2, 3, 3
  88. -- SWAP2
  89. stack: 3, 3, 2
  90. -- DUP
  91. stack: 3, 3, 2, 2
  92. -- SWAP3
  93. stack: 2, 3, 2, 3
  94. -- ADD
  95. stack: 2, 3, 5
  96. -- DUP
  97. stack: 2, 3, 5, 5
  98. -- PRINT
  99. ++ PRINT: 5
  100. stack: 2, 3, 5
  101. -- DUP
  102. stack: 2, 3, 5, 5
  103. -- PUSH 10
  104. stack: 2, 3, 5, 5, 10
  105. -- SWAP1
  106. stack: 2, 3, 5, 10, 5
  107. -- MOD
  108. stack: 2, 3, 5, 5
  109. -- PUSH 0
  110. stack: 2, 3, 5, 5, 0
  111. -- NE
  112. stack: 2, 3, 5, 1
  113. -- JMPZ 2000
  114. stack: 2, 3, 5
  115. -- SWAP1
  116. stack: 2, 5, 3
  117. -- SWAP2
  118. stack: 3, 5, 2
  119. -- POP
  120. stack: 3, 5
  121. -- JMP 1000
  122. stack: 3, 5
  123. -- LABEL 1000
  124. stack: 3, 5
  125. -- DUP
  126. stack: 3, 5, 5
  127. -- SWAP2
  128. stack: 5, 5, 3
  129. -- DUP
  130. stack: 5, 5, 3, 3
  131. -- SWAP3
  132. stack: 3, 5, 3, 5
  133. -- ADD
  134. stack: 3, 5, 8
  135. -- DUP
  136. stack: 3, 5, 8, 8
  137. -- PRINT
  138. ++ PRINT: 8
  139. stack: 3, 5, 8
  140. -- DUP
  141. stack: 3, 5, 8, 8
  142. -- PUSH 10
  143. stack: 3, 5, 8, 8, 10
  144. -- SWAP1
  145. stack: 3, 5, 8, 10, 8
  146. -- MOD
  147. stack: 3, 5, 8, 8
  148. -- PUSH 0
  149. stack: 3, 5, 8, 8, 0
  150. -- NE
  151. stack: 3, 5, 8, 1
  152. -- JMPZ 2000
  153. stack: 3, 5, 8
  154. -- SWAP1
  155. stack: 3, 8, 5
  156. -- SWAP2
  157. stack: 5, 8, 3
  158. -- POP
  159. stack: 5, 8
  160. -- JMP 1000
  161. stack: 5, 8
  162. -- LABEL 1000
  163. stack: 5, 8
  164. -- DUP
  165. stack: 5, 8, 8
  166. -- SWAP2
  167. stack: 8, 8, 5
  168. -- DUP
  169. stack: 8, 8, 5, 5
  170. -- SWAP3
  171. stack: 5, 8, 5, 8
  172. -- ADD
  173. stack: 5, 8, 13
  174. -- DUP
  175. stack: 5, 8, 13, 13
  176. -- PRINT
  177. ++ PRINT: 13
  178. stack: 5, 8, 13
  179. -- DUP
  180. stack: 5, 8, 13, 13
  181. -- PUSH 10
  182. stack: 5, 8, 13, 13, 10
  183. -- SWAP1
  184. stack: 5, 8, 13, 10, 13
  185. -- MOD
  186. stack: 5, 8, 13, 3
  187. -- PUSH 0
  188. stack: 5, 8, 13, 3, 0
  189. -- NE
  190. stack: 5, 8, 13, 1
  191. -- JMPZ 2000
  192. stack: 5, 8, 13
  193. -- SWAP1
  194. stack: 5, 13, 8
  195. -- SWAP2
  196. stack: 8, 13, 5
  197. -- POP
  198. stack: 8, 13
  199. -- JMP 1000
  200. stack: 8, 13
  201. -- LABEL 1000
  202. stack: 8, 13
  203. -- DUP
  204. stack: 8, 13, 13
  205. -- SWAP2
  206. stack: 13, 13, 8
  207. -- DUP
  208. stack: 13, 13, 8, 8
  209. -- SWAP3
  210. stack: 8, 13, 8, 13
  211. -- ADD
  212. stack: 8, 13, 21
  213. -- DUP
  214. stack: 8, 13, 21, 21
  215. -- PRINT
  216. ++ PRINT: 21
  217. stack: 8, 13, 21
  218. -- DUP
  219. stack: 8, 13, 21, 21
  220. -- PUSH 10
  221. stack: 8, 13, 21, 21, 10
  222. -- SWAP1
  223. stack: 8, 13, 21, 10, 21
  224. -- MOD
  225. stack: 8, 13, 21, 1
  226. -- PUSH 0
  227. stack: 8, 13, 21, 1, 0
  228. -- NE
  229. stack: 8, 13, 21, 1
  230. -- JMPZ 2000
  231. stack: 8, 13, 21
  232. -- SWAP1
  233. stack: 8, 21, 13
  234. -- SWAP2
  235. stack: 13, 21, 8
  236. -- POP
  237. stack: 13, 21
  238. -- JMP 1000
  239. stack: 13, 21
  240. -- LABEL 1000
  241. stack: 13, 21
  242. -- DUP
  243. stack: 13, 21, 21
  244. -- SWAP2
  245. stack: 21, 21, 13
  246. -- DUP
  247. stack: 21, 21, 13, 13
  248. -- SWAP3
  249. stack: 13, 21, 13, 21
  250. -- ADD
  251. stack: 13, 21, 34
  252. -- DUP
  253. stack: 13, 21, 34, 34
  254. -- PRINT
  255. ++ PRINT: 34
  256. stack: 13, 21, 34
  257. -- DUP
  258. stack: 13, 21, 34, 34
  259. -- PUSH 10
  260. stack: 13, 21, 34, 34, 10
  261. -- SWAP1
  262. stack: 13, 21, 34, 10, 34
  263. -- MOD
  264. stack: 13, 21, 34, 4
  265. -- PUSH 0
  266. stack: 13, 21, 34, 4, 0
  267. -- NE
  268. stack: 13, 21, 34, 1
  269. -- JMPZ 2000
  270. stack: 13, 21, 34
  271. -- SWAP1
  272. stack: 13, 34, 21
  273. -- SWAP2
  274. stack: 21, 34, 13
  275. -- POP
  276. stack: 21, 34
  277. -- JMP 1000
  278. stack: 21, 34
  279. -- LABEL 1000
  280. stack: 21, 34
  281. -- DUP
  282. stack: 21, 34, 34
  283. -- SWAP2
  284. stack: 34, 34, 21
  285. -- DUP
  286. stack: 34, 34, 21, 21
  287. -- SWAP3
  288. stack: 21, 34, 21, 34
  289. -- ADD
  290. stack: 21, 34, 55
  291. -- DUP
  292. stack: 21, 34, 55, 55
  293. -- PRINT
  294. ++ PRINT: 55
  295. stack: 21, 34, 55
  296. -- DUP
  297. stack: 21, 34, 55, 55
  298. -- PUSH 10
  299. stack: 21, 34, 55, 55, 10
  300. -- SWAP1
  301. stack: 21, 34, 55, 10, 55
  302. -- MOD
  303. stack: 21, 34, 55, 5
  304. -- PUSH 0
  305. stack: 21, 34, 55, 5, 0
  306. -- NE
  307. stack: 21, 34, 55, 1
  308. -- JMPZ 2000
  309. stack: 21, 34, 55
  310. -- SWAP1
  311. stack: 21, 55, 34
  312. -- SWAP2
  313. stack: 34, 55, 21
  314. -- POP
  315. stack: 34, 55
  316. -- JMP 1000
  317. stack: 34, 55
  318. -- LABEL 1000
  319. stack: 34, 55
  320. -- DUP
  321. stack: 34, 55, 55
  322. -- SWAP2
  323. stack: 55, 55, 34
  324. -- DUP
  325. stack: 55, 55, 34, 34
  326. -- SWAP3
  327. stack: 34, 55, 34, 55
  328. -- ADD
  329. stack: 34, 55, 89
  330. -- DUP
  331. stack: 34, 55, 89, 89
  332. -- PRINT
  333. ++ PRINT: 89
  334. stack: 34, 55, 89
  335. -- DUP
  336. stack: 34, 55, 89, 89
  337. -- PUSH 10
  338. stack: 34, 55, 89, 89, 10
  339. -- SWAP1
  340. stack: 34, 55, 89, 10, 89
  341. -- MOD
  342. stack: 34, 55, 89, 9
  343. -- PUSH 0
  344. stack: 34, 55, 89, 9, 0
  345. -- NE
  346. stack: 34, 55, 89, 1
  347. -- JMPZ 2000
  348. stack: 34, 55, 89
  349. -- SWAP1
  350. stack: 34, 89, 55
  351. -- SWAP2
  352. stack: 55, 89, 34
  353. -- POP
  354. stack: 55, 89
  355. -- JMP 1000
  356. stack: 55, 89
  357. -- LABEL 1000
  358. stack: 55, 89
  359. -- DUP
  360. stack: 55, 89, 89
  361. -- SWAP2
  362. stack: 89, 89, 55
  363. -- DUP
  364. stack: 89, 89, 55, 55
  365. -- SWAP3
  366. stack: 55, 89, 55, 89
  367. -- ADD
  368. stack: 55, 89, 144
  369. -- DUP
  370. stack: 55, 89, 144, 144
  371. -- PRINT
  372. ++ PRINT: 144
  373. stack: 55, 89, 144
  374. -- DUP
  375. stack: 55, 89, 144, 144
  376. -- PUSH 10
  377. stack: 55, 89, 144, 144, 10
  378. -- SWAP1
  379. stack: 55, 89, 144, 10, 144
  380. -- MOD
  381. stack: 55, 89, 144, 4
  382. -- PUSH 0
  383. stack: 55, 89, 144, 4, 0
  384. -- NE
  385. stack: 55, 89, 144, 1
  386. -- JMPZ 2000
  387. stack: 55, 89, 144
  388. -- SWAP1
  389. stack: 55, 144, 89
  390. -- SWAP2
  391. stack: 89, 144, 55
  392. -- POP
  393. stack: 89, 144
  394. -- JMP 1000
  395. stack: 89, 144
  396. -- LABEL 1000
  397. stack: 89, 144
  398. -- DUP
  399. stack: 89, 144, 144
  400. -- SWAP2
  401. stack: 144, 144, 89
  402. -- DUP
  403. stack: 144, 144, 89, 89
  404. -- SWAP3
  405. stack: 89, 144, 89, 144
  406. -- ADD
  407. stack: 89, 144, 233
  408. -- DUP
  409. stack: 89, 144, 233, 233
  410. -- PRINT
  411. ++ PRINT: 233
  412. stack: 89, 144, 233
  413. -- DUP
  414. stack: 89, 144, 233, 233
  415. -- PUSH 10
  416. stack: 89, 144, 233, 233, 10
  417. -- SWAP1
  418. stack: 89, 144, 233, 10, 233
  419. -- MOD
  420. stack: 89, 144, 233, 3
  421. -- PUSH 0
  422. stack: 89, 144, 233, 3, 0
  423. -- NE
  424. stack: 89, 144, 233, 1
  425. -- JMPZ 2000
  426. stack: 89, 144, 233
  427. -- SWAP1
  428. stack: 89, 233, 144
  429. -- SWAP2
  430. stack: 144, 233, 89
  431. -- POP
  432. stack: 144, 233
  433. -- JMP 1000
  434. stack: 144, 233
  435. -- LABEL 1000
  436. stack: 144, 233
  437. -- DUP
  438. stack: 144, 233, 233
  439. -- SWAP2
  440. stack: 233, 233, 144
  441. -- DUP
  442. stack: 233, 233, 144, 144
  443. -- SWAP3
  444. stack: 144, 233, 144, 233
  445. -- ADD
  446. stack: 144, 233, 377
  447. -- DUP
  448. stack: 144, 233, 377, 377
  449. -- PRINT
  450. ++ PRINT: 377
  451. stack: 144, 233, 377
  452. -- DUP
  453. stack: 144, 233, 377, 377
  454. -- PUSH 10
  455. stack: 144, 233, 377, 377, 10
  456. -- SWAP1
  457. stack: 144, 233, 377, 10, 377
  458. -- MOD
  459. stack: 144, 233, 377, 7
  460. -- PUSH 0
  461. stack: 144, 233, 377, 7, 0
  462. -- NE
  463. stack: 144, 233, 377, 1
  464. -- JMPZ 2000
  465. stack: 144, 233, 377
  466. -- SWAP1
  467. stack: 144, 377, 233
  468. -- SWAP2
  469. stack: 233, 377, 144
  470. -- POP
  471. stack: 233, 377
  472. -- JMP 1000
  473. stack: 233, 377
  474. -- LABEL 1000
  475. stack: 233, 377
  476. -- DUP
  477. stack: 233, 377, 377
  478. -- SWAP2
  479. stack: 377, 377, 233
  480. -- DUP
  481. stack: 377, 377, 233, 233
  482. -- SWAP3
  483. stack: 233, 377, 233, 377
  484. -- ADD
  485. stack: 233, 377, 610
  486. -- DUP
  487. stack: 233, 377, 610, 610
  488. -- PRINT
  489. ++ PRINT: 610
  490. stack: 233, 377, 610
  491. -- DUP
  492. stack: 233, 377, 610, 610
  493. -- PUSH 10
  494. stack: 233, 377, 610, 610, 10
  495. -- SWAP1
  496. stack: 233, 377, 610, 10, 610
  497. -- MOD
  498. stack: 233, 377, 610, 0
  499. -- PUSH 0
  500. stack: 233, 377, 610, 0, 0
  501. -- NE
  502. stack: 233, 377, 610, 0
  503. -- JMPZ 2000
  504. stack: 233, 377, 610
  505. -- LABEL 2000
  506. stack: 233, 377, 610

11.2 重写step函数

  1. /*
  2. 0 表示状态
  3. 2 表示跳
  4. */
  5. function step($stack, $shallow, $deep, $action, $immediate)
  6. {
  7. if($action == 'JMP' ){
  8. array(0, $stack, $shallow, $deep);
  9. array(1);
  10. array(2, $jump)
  11. }
  12. }

11.3 运行举例

  1. execute('PUSH 0 LOAD PUSH 1000 GT JMPZ 1000 HALT LABEL 1000 PUSH 1 LOAD PUSH 200 SWAP1 WRITE');
  2. /*
  3. associative array
  4. 6820 -> 200
  5. 1977 -> 100
  6. PUSH 100 PUSH 6820 WRITE
  7. PUSH 200 PUSH 1977 WRITE
  8. PUSH 1977 READ
  9. PUSH 6820 READ
  10. */

11.4 代码

第18次课程代码

  1. $program = 'PUSH 0 LOAD PUSH 1000 GT JMPZ 1000 HALT LABEL 1000 PUSH 1 LOAD PUSH 200 SWAP1 WRITE';
  2. list($shallow, $deep) = execute($program, array(0 => 2000, 1 => 7440), array(7440 => 100, 6508 => 200));
  3. var_dump($deep);
  4. /*
  5. associative array
  6. 6820 -> 200
  7. 1977 -> 100
  8. PUSH 100 PUSH 6820 WRITE
  9. PUSH 200 PUSH 1977 WRITE
  10. PUSH 1977 READ
  11. PUSH 6820 READ
  12. */
  13. function convert($string) {
  14. $operations = array();
  15. $_0000 = explode(' ', $string);
  16. $pieces = array();
  17. foreach ($_0000 as $_0001) {
  18. $_0001 = trim($_0001);
  19. if (strlen($_0001) > 0)
  20. { $pieces[] = $_0001; }
  21. }
  22. $index = 0;
  23. while ($index < count($pieces)) {
  24. if ($pieces[$index] == 'PUSH' || $pieces[$index] == 'LABEL' || $pieces[$index] == 'JMP' || $pieces[$index] == 'JMPZ') {
  25. $operations[] = array($pieces[$index], $pieces[$index + 1]);
  26. $index += 2;
  27. continue;
  28. }
  29. $operations[] = array($pieces[$index]);
  30. $index++;
  31. }
  32. return $operations;
  33. }
  34. function render($stack) {
  35. $_0000 = '';
  36. foreach ($stack as $_0001) {
  37. $_0000 = sprintf('%s, %d', $_0000, $_0001);
  38. }
  39. return substr($_0000, 2);
  40. }
  41. function execute($string, $shallow, $deep) {
  42. return execute_0984(convert($string), $shallow, $deep);
  43. }
  44. function execute_0984($operations, $shallow, $deep) {
  45. $stack = array();
  46. echo sprintf('stack: %s%c', render($stack), 10);
  47. $index = 0;
  48. $length = count($operations);
  49. while($index < $length) {
  50. $_0000 = $operations[$index];
  51. echo sprintf('-- %s %s%c', $_0000[0], isset($_0000[1])? strval($_0000[1]): '', 10);
  52. $bundle = step($stack, $shallow, $deep, $_0000[0], $_0000[1]);
  53. if ($bundle[0] == 0) {
  54. echo sprintf('stack: %s%c', render($bundle[1]), 10);
  55. $stack = $bundle[1];
  56. $shallow = $bundle[2];
  57. $deep = $bundle[3];
  58. $index++;
  59. continue;
  60. }
  61. if ($bundle[0] == 1) {
  62. echo sprintf('-- SPECIAL EVENT: HALTED!! DIED!!%c', 10);
  63. break;
  64. }
  65. if ($bundle[0] == 2) {
  66. $index = find($operations, $bundle[2]);
  67. $stack = $bundle[1];
  68. if ($index == -1)
  69. { die('INVALID ADDRESS!!'); }
  70. continue;
  71. }
  72. }
  73. return array($shallow, $deep);
  74. }
  75. function find($operations, $label) {
  76. $index = 0;
  77. while ($index < count($operations)) {
  78. if ($operations[$index][0] != 'LABEL')
  79. { $index++; continue; }
  80. if ($operations[$index][35] == $label)
  81. { return $index; }
  82. $index++;
  83. }
  84. return -1;
  85. }
  86. function step($stack, $shallow, $deep, $action, $immediate)
  87. {
  88. if ($action == 'ADD') {
  89. $a = array_pop($stack);
  90. $b = array_pop($stack);
  91. array_push($stack, $a + $b);
  92. return array(0, $stack, $shallow, $deep);
  93. }
  94. if ($action == 'SUB') {
  95. $a = array_pop($stack);
  96. $b = array_pop($stack);
  97. array_push($stack, $a - $b);
  98. return array(0, $stack, $shallow, $deep);
  99. }
  100. if ($action == 'MUL') {
  101. $a = array_pop($stack);
  102. $b = array_pop($stack);
  103. array_push($stack, $a * $b);
  104. return array(0, $stack, $shallow, $deep);
  105. }
  106. if ($action == 'DIV') {
  107. $a = array_pop($stack);
  108. $b = array_pop($stack);
  109. array_push($stack, floor($a / $b));
  110. return array(0, $stack, $shallow, $deep);
  111. }
  112. if ($action == 'MOD') {
  113. $a = array_pop($stack);
  114. $b = array_pop($stack);
  115. array_push($stack, $a % $b);
  116. return array(0, $stack, $shallow, $deep);
  117. }
  118. if ($action == 'LT') {
  119. $a = array_pop($stack);
  120. $b = array_pop($stack);
  121. array_push($stack, $a < $b? 1: 0);
  122. return array(0, $stack, $shallow, $deep);
  123. }
  124. if ($action == 'LTE') {
  125. $a = array_pop($stack);
  126. $b = array_pop($stack);
  127. array_push($stack, $a <= $b? 1: 0);
  128. return array(0, $stack, $shallow, $deep);
  129. }
  130. if ($action == 'EQ') {
  131. $a = array_pop($stack);
  132. $b = array_pop($stack);
  133. array_push($stack, $a == $b? 1: 0);
  134. return array(0, $stack, $shallow, $deep);
  135. }
  136. if ($action == 'NE') {
  137. $a = array_pop($stack);
  138. $b = array_pop($stack);
  139. array_push($stack, $a != $b? 1: 0);
  140. return array(0, $stack, $shallow, $deep);
  141. }
  142. if ($action == 'GT') {
  143. $a = array_pop($stack);
  144. $b = array_pop($stack);
  145. array_push($stack, $a > $b? 1: 0);
  146. return array(0, $stack, $shallow, $deep);
  147. }
  148. if ($action == 'GTE') {
  149. $a = array_pop($stack);
  150. $b = array_pop($stack);
  151. array_push($stack, $a >= $b? 1: 0);
  152. return array(0, $stack, $shallow, $deep);
  153. }
  154. if ($action == 'AND') {
  155. $a = array_pop($stack);
  156. $b = array_pop($stack);
  157. array_push($stack, boolval($a) && boolval($b)? 1: 0);
  158. return array(0, $stack, $shallow, $deep);
  159. }
  160. if ($action == 'OR') {
  161. $a = array_pop($stack);
  162. $b = array_pop($stack);
  163. array_push($stack, boolval($a) || boolval($b)? 1: 0);
  164. return array(0, $stack, $shallow, $deep);
  165. }
  166. if ($action == 'XOR') {
  167. $a = array_pop($stack);
  168. $b = array_pop($stack);
  169. array_push($stack, (boolval($a) && ! boolval($b)) || (! boolval($a) && boolval($b))? 1: 0);
  170. return array(0, $stack, $shallow, $deep);
  171. }
  172. if ($action == 'NOT') {
  173. $a = array_pop($stack);
  174. array_push($stack, boolval($a)? 0: 1);
  175. return array(0, $stack, $shallow, $deep);
  176. }
  177. if ($action == 'JMP') {
  178. return array(2, $stack, $immediate);
  179. }
  180. if ($action == 'JMPZ') {
  181. $a = array_pop($stack);
  182. if ($a == 0)
  183. return array(2, $stack, $immediate);
  184. return array(0, $stack, $shallow, $deep);
  185. }
  186. if ($action == 'LABEL') {
  187. return array(0, $stack, $shallow, $deep);
  188. }
  189. if ($action == 'HALT') {
  190. return array(1);
  191. }
  192. if ($action == 'PUSH') {
  193. array_push($stack, $immediate);
  194. return array(0, $stack, $shallow, $deep);
  195. }
  196. if ($action == 'POP') {
  197. array_pop($stack);
  198. return array(0, $stack, $shallow, $deep);
  199. }
  200. if ($action == 'DUP') {
  201. $a = array_pop($stack);
  202. array_push($stack, $a);
  203. array_push($stack, $a);
  204. return array(0, $stack, $shallow, $deep);
  205. }
  206. if ($action == 'STORE') {
  207. $a = array_pop($stack);
  208. $b = array_pop($stack);
  209. $shallow[$a] = $b;
  210. return array(0, $stack, $shallow, $deep);
  211. }
  212. if ($action == 'LOAD') {
  213. $a = array_pop($stack);
  214. array_push($stack, isset($shallow[$a]) ? $shallow[$a] : 0);
  215. return array(0, $stack, $shallow, $deep);
  216. }
  217. if ($action == 'WRITE') {
  218. $a = array_pop($stack);
  219. $b = array_pop($stack);
  220. $deep[$a] = $b;
  221. return array(0, $stack, $shallow, $deep);
  222. }
  223. if ($action == 'READ') {
  224. $a = array_pop($stack);
  225. array_push($stack, isset($deep[$a]) ? $deep[$a] : 0);
  226. return array(0, $stack, $shallow, $deep);
  227. }
  228. if ($action == 'SWAP1') {
  229. $a = array_pop($stack);
  230. $b = array_pop($stack);
  231. array_push($stack, $a);
  232. array_push($stack, $b);
  233. return array(0, $stack, $shallow, $deep);
  234. }
  235. if ($action == 'SWAP2') {
  236. $a = array_pop($stack);
  237. $b = array_pop($stack);
  238. $c = array_pop($stack);
  239. array_push($stack, $a);
  240. array_push($stack, $b);
  241. array_push($stack, $c);
  242. return array(0, $stack, $shallow, $deep);
  243. }
  244. if ($action == 'SWAP3') {
  245. $a = array_pop($stack);
  246. $b = array_pop($stack);
  247. $c = array_pop($stack);
  248. $d = array_pop($stack);
  249. array_push($stack, $a);
  250. array_push($stack, $c);
  251. array_push($stack, $b);
  252. array_push($stack, $d);
  253. return array(0, $stack, $shallow, $deep);
  254. }
  255. }

执行结果:

  1. stack:
  2. -- PUSH 0
  3. stack: 0
  4. -- LOAD
  5. stack: 2000
  6. -- PUSH 1000
  7. stack: 2000, 1000
  8. -- GT
  9. stack: 0
  10. -- JMPZ 1000
  11. -- LABEL 1000
  12. stack:
  13. -- PUSH 1
  14. stack: 1
  15. -- LOAD
  16. stack: 7440
  17. -- PUSH 200
  18. stack: 7440, 200
  19. -- SWAP1
  20. stack: 200, 7440
  21. -- WRITE
  22. stack:
  23. array(2) {
  24. [7440]=>
  25. string(3) "200"
  26. [6508]=>
  27. int(200)
  28. }

16. 资料链接

课程相关链接

课程直播地址:
http://www.itdks.com/dakashuo/playback/1428

第13次课程屏幕录屏:
http://pan.baidu.com/s/1nviNO1b

老师开发的wiki,记录一些知识:
http://d111.learningchain.cn

比特币与区块链介绍

对未来产生影响最大的科技
http://open.163.com/movie/2016/9/P/1/MC0Q7LQR3_MC0Q97OP1.html

比特币原理图示与解释
https://visual.ly/community/infographic/technology/bitcoin-infographic

区块链技术文档

Bitcoin: A Peer-to-Peer Electronic Cash System, Satoshi Nakamoto
https://bitcoin.org/bitcoin.pdf

比特币白皮书:一种点对点的电子现金系统 中文翻译版, 中本聪
http://www.8btc.com/wiki/bitcoin-a-peer-to-peer-electronic-cash-system

GitHub - bitcoinbook/bitcoinbook: Mastering Bitcoin 2nd Edition - Programming the Open Blockchain https://github.com/bitcoinbook/bitcoinbook
精通比特币中文第1版
http://book.8btc.com/master_bitcoin
精通比特币第二版中文版
http://book.8btc.com/masterbitcoin2cn

Merkle Tree(默克尔树)算法解析
http://blog.csdn.net/wo541075754/article/details/54632929

介绍几本关于比特币和区块链的书
https://www.zhihu.com/question/35541188

比特币背后的密码学原理
http://www.jianshu.com/p/225ff9439132

侧链

解释与白皮书:
A SIMPLE EXPLANATION OF BITCOIN “SIDECHAINS”
https://gendal.me/2014/10/26/a-simple-explanation-of-bitcoin-sidechains/

sidechains
https://www.slideshare.net/crainbf/sidechains-presentation

blockstream公司的开源侧链模板项目elements:
https://elementsproject.org/

区块链架构与开发

区块链技术可视化演示

演示视频:
http://www.iqiyi.com/w_19ruazv201.html
演示学习网站:
http://blockchaindemo.io/
https://anders.com/blockchain/
可视化演示代码:
https://github.com/anders94/blockchain-demo

bitcoin script

bitcoin Script wiki说明
https://en.bitcoin.it/wiki/Script

在线script演示

https://webbtc.com/script
http://www.crmarsh.com/script-playground/

比特币开发

官方网站开发
https://bitcoin.org/en/development
https://bitcoin.org/en/developer-guide

bitcoin wiki(非官方,确是最完整的比特币文档wiki)
https://en.bitcoin.it/wiki/Main_Page

bitcoin 协议规格
https://en.bitcoin.it/wiki/Protocol_documentation

比特币难度公式:
https://en.bitcoin.it/Difficulty
https://en.bitcoin.it/wiki/Target

其实并没有什么比特币,只有 UTXO
http://8btc.com/article-4381-1.html
比特币UTXO的原理?
https://www.zhihu.com/question/59913301

区块链应用

区块链技术是什么?未来可能用于哪些方面?
https://www.zhihu.com/question/27687960

https://blockchain.info/

以太坊

wiki
https://github.com/ethereum/wiki/wiki
以太坊白皮书
https://github.com/ethereum/wiki/wiki/White-Paper
以太坊白皮书中文版
https://github.com/ethereum/wiki/wiki/%5B%E4%B8%AD%E6%96%87%5D-%E4%BB%A5%E5%A4%AA%E5%9D%8A%E7%99%BD%E7%9A%AE%E4%B9%A6
http://8btc.com/thread-2918-1-1.html

以太坊黄皮书英文版
https://ethereum.github.io/yellowpaper/paper.pdf
以太坊黄皮书中文版(关于以太坊技术的实现规范)
https://github.com/yuange1024/ethereum_yellowpaper/blob/master/Paper_Chinese.pdf
http://download.cxyym.com/blockchain/ethereum_yellowpaper_cn.pdf

网上比特币相关公开课程

在线演示区块链原理:
http://blockchaindemo.io/
http://anders.com/blockchain/

比特币和数字货币技术-Princeton University课程
https://www.coursera.org/learn/cryptocurrency

斯坦福大学公开课MOOC:比特币工程学
https://bitcoin.stanford.edu/

计算机基础

什么是图灵完备?
https://www.zhihu.com/question/20115374

内存堆和栈的区别
http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html
数据结构之用栈实现逆波兰表达式
http://www.codes51.com/article/detail_1076640.html

parrot 虚拟机
http://www.oschina.net/p/parrot
php的数组的实现介绍
http://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html

编程语言

php file 函数教程:
http://www.w3school.com.cn/php/php_ref_filesystem.asp

虚拟机原理与实现

How to implement a simple dalvik virtual machine
https://www.slideshare.net/ssusere3af56/how-to-implement-a-simple-dalvik-virtual-machine
register简单虚拟机
http://www.cnblogs.com/unixfy/p/3280264.html
基于栈的虚拟机的实现
http://www.cppblog.com/kevinlynx/archive/2010/04/15/112704.html
栈虚拟机源码剖析
http://www.cnblogs.com/unixfy/p/3335874.html
实现一个堆栈虚拟机
http://www.cnblogs.com/unixfy/p/3337917.html

网络编程

beej's Guide to Network Programming(2016)

UNIX Network Programming(1990) by W Richard Stevens

https://www.kernel.org/doc/man-pages Michael kerrish维护,网站分为8个部分

利用select/poll监听多个设备详解
http://blog.csdn.net/qq_28090573/article/details/51094321

密码学基础:

密码学算法应用机制
https://www.zybuluo.com/zhongdao/note/950527

一个图文并茂的比特币与其中应用的密码学算法的入门简介文章:
https://www.myblockchainblog.com/blog/blockchain-cryptography

What is a Digital Signature?
http://www.youdzone.com/signature.html

markdown 编辑器

markdown editor:
https://github.com/cloose/CuteMarkEd
cmd markdown editor:
https://www.zybuluo.com/

区块链技术公开课三期的公众号报道

http://mp.weixin.qq.com/s/GKXUHEHd44mGqH05SgRkBA
http://mp.weixin.qq.com/s/d0hBmFFqxWl995ZbEKqkHw
http://mp.weixin.qq.com/s/qoVkB_xzaoRNAPkaPJWddw
http://mp.weixin.qq.com/s/kF_G9bkefJdbx24wcoJ0IA
http://mp.weixin.qq.com/s/hZi0RFrjMEYCdVsiE95E6w

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注