[关闭]
@zhongdao 2018-02-26T07:46:45.000000Z 字数 99700 阅读 10377

区块链设计与实现笔记v1


拟定目录大纲:
0. 前言
1. 区块链原理机制与背景
2. 区块链基本结构
3. 加解密算法实现
4. 区块数据结构从定义到初步实现
5. 区块节点读取与验证
6. 节点和应用程序之间协议
7. 节点之间沟通
8. 侧链设计原理
9. 侧链开发
10. 智能合约设计原理
11. 智能合约开发
12. 计算机基础
13. Linux相关说明
14. 程序开发语言相关说明
15. 密码学相关说明
16. 资料链接

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

实际自动导航目录:

目录不可见时访问: https://www.zybuluo.com/zhongdao/note/933849

0.前言

0.1 内容来源

区块链技术开发公开课:
授课老师: 辕询, 李涛涛
直播地址: http://www.itdks.com/dakashuo/playback/1428

0.2 笔记缘起

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

0.3 内容概要

创造一个易于理解说明的区块链.从理论到程序实现.
为了便于对编程不熟悉的同学学习和备查,也增加了所需要的相关的内容.

具体内容参考本文目录,

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

0.4 第三期每次课程摘要

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

通过有限状态机(Finite State Machine)对接收的区块数据进行验证。

以后的规划:
- 测试验证函数
- 每一个C协议的操作落实
- 支持超过一个私钥
- 生成一个文件来保存别的节点的IP和端口为下次连接做准备
- 扔掉我们造的storage,改用SQL
最大的2个目标:
- 智能合约 smart contracts
- 侧链 sidechains.

1. 区块链原理机制与背景

1.1 解释比特币

2008年,署名中本聪的作者在讨论加密的邮件列表中,发表论文:A Peer to Peer Electronic Cash System. 2009年1月,Bitcoin网络诞生,代码开源.

比特币(bitcoin),一种去中心化的点对点的网上货币,在没有任何资产担保、内在价值或者中心发行者的情况下维持着价值。
传统互联网解决了信息的传递,而基于区块链的比特币解决了价值的传递.

image_1buj0opft18mi1a03c0l159uq2c9.png-1980kB

1.2 区块链与比特币机制图示

区块链起源于bitcoin,
通过分布式账本,去中心化的存储,去第三方中介,解决了信任问题.

以区块链技术为核心的系统会形成如下的效果:
1. 全球化的, 没有中心节点, 数据分布式地存储在系统的各个节点上, 即使绝大部分节点毁灭了,只要还有1个节点存在,就可以重建并还原区块链数据.
2. 自治的交易体系,所有节点都是对等的,每个节点都可以自由加入和离开,按照相同的规则达成共识,自行产生区块并且同步数据,无需人工参与.
3. 按照合约执行,各个节点按照既定的运行规则执行,一旦出现违背规则的行为,就会被其他节点抛弃;智能合约包括在每个交易中,交易验证必须先运行智能合约,只有通过验证交易才能被接受.
4. 数据公开透明,不能被篡改,交易之间有一定的关联性,容易追溯.

image_1buitr1v0ojt118id6k1jtj11ev9.png-75.6kB
image_1buj01tth17m61cue25019hn1fjem.png-442.9kB

下图是比特币的交易的运行机制解释:
image_1buj0cbak1gllvcn1f701k9qfag13.png-1568.3kB

1.2.1 区块链应用

image_1bv2evsfusq05n1uj21bmlvph1t.png-202.8kB
Below is a quick description of each of the use cases:

App development: Proof of ownership of modules in app development

Digital content: Proof of ownership for digital content storage and delivery

Ride-sharing: Points-based value transfer for ride-sharing

Digital security trading: Ownership and transfer

Digitization of documents/contracts: Digitization of documents/contracts and proof of ownership for transfers

Decentralized storage: Decentralized storage using a network of computers on blockchain

Company incorporations: Digitizing company incorporations, transfer of equity/ownership and governance

Decentralized Internet and computing resources: Decentralized Internet and computing resources to cover every home and business

Home automation: Platform to link the home network and electrical devices to the cloud

Digital identity: Provides digital identity that protects consumer privacy

Escrow/custodian service: Escrow/custodian service for the gaming industry; loan servicing and e-commerce

IT portal: A smart contract IT portal executing order fulfillment in ecommerce/manufacturing

Patient records: Decentralized patient records management

Digitizing assets: Improves anti-counterfeit measures

Reputation management: Helps users engage, share reputation and collect feedback

Prediction platform: Decentralized prediction platform for the share markets, elections, etc.

Enables authenticity of a review: Enables authenticity of a review through trustworthy endorsements for employee peer reviews

Marketplace for sales and purchases of digital assets: Proof of ownership and a marketplace for sales and purchases of digital assets

1.3 区块链数据结构图示

在比特币社区里,Transaction 被简称为 TX

https://en.bitcoin.it/wiki/Protocol_documentation

区块链概要图示
image_1bv2elk621lm217m71nkm6kf1ot1g.png-16.5kB

交易图示
image_1bv2ecblhong1b7h15pknvb1q81m.png-10.8kB
交易与基本节点结构

image_1bv2f86h1nofrhcu8ef60hs9.png-37.2kB
没有余额的概念, 一个人的资产来自以往的所有交易.

image_1bv2eauqno6qt9a1rlg5i91io89.png-21.8kB

1.4 知识点

UTXO

UTXO 代表 Unspent Transaction Output。
image_1bv3fk4q679aod31l3t1n7vc3l13.png-91.4kB
要理解UTXO,最简单的办法就是把一枚比特币从诞生到在商海中沉浮的经历描述一下。我们假设一个这样的场景:张三挖到12.5 枚比特币。过了几天,他把其中 2.5 枚支付给李四。又过了几天,他和李四各出资 2.5 比特币凑成 5 比特币付给王五。

如果是基于账户的设计,张、李、王三人在数据库中各有一个账户,则他们三人的账户变化如下图所示:
image_1bv3fb55b1jfjiin1t0a1spc3jp9.png-161kB
在比特币中,这个过程是通过 UTXO 实现的,图示如下:
image_1bv3fcdkf7lo17n16cfg981thnm.png-313.1kB
上图来自: http://8btc.com/article-4381-1.html
当我们说张三拥有 10枚比特币的时候,我实际上是说,当前区块链账本中,有若干笔交易的 UTXO 项收款人写的是张三的地址,而这些 UTXO 项的数额总和是 10。因为在比特币系统里,一个人可以拥有的地址资源,可谓取之不尽用之不竭。要知道自己的一大堆地址里一共收了多少UTXO,人是算不过来的,需要由比特币钱包代为跟踪计算。

SPV

钱包不用下载所有的交易记录就能验证.

钱包

2012 发明了思维钱包的概念, 容易猜, 钱被偷盗的可能性增加了.

冷钱包:
所有的私钥都是从数字来的, 从随机生产器来的. 自己指定的

不联网的计算机, 把数字存在上面.
联网的计算机把不签名的交易 放在u盘上, 然后

理论上, 病毒影响 U盘.
更安全的是, 造一个地址, 从来不发钱. 只用来收钱.
发一次, 冷地址就变热地址了.

1.5 安全性

image_1bv2effac1nbs12f9d8dvs61h4p13.png-9.6kB

50% Attack 百分之五十攻击
控制超过51%算力的时候, 可以修改节点程序, 忽略某种交易.
也可以从一个旧节点开始,建立一条新的节点链,超过旧节点后的节点长度后, 原来就节点上的所有交易就被废弃了, 因为所有节点都开始挖最长的节点.
image_1bv4jepkmule19imp921riu10l41g.png-116kB
image_1bv4jdt34f601sdcdoccd510ga13.png-104.2kB

image_1bv4jgteukkg1qumdoov9h11l32d.png-156.3kB

Transaction Malleability Attack 交易挠曲攻击

Double Spending Attack 重叠耗资攻击

Replay Attack 重放攻击
分叉时

DDoS Attack 分布服务扣缴攻击

Delay Attack 延迟攻击

Partition Attack 割据攻击

1.6 比特币特性

Signing-Only Wallets
两台电脑, 一个台连接网络,运行节点钱包,但没有私钥. 另外一台没网络的把私钥放上去.
这样能防止任何网络上的攻击者来偷钥匙钥匙.
很多企业都是这么做的. 对于复杂的usb病毒, windows之间用过的u盘, 放到linux下格式化.

这个的严格程度,还不如cold Wallets, 创造私钥,打印出来,毁灭计算机. 用时再输入到计算机.

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

设计理念

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的设计理念。

2.2 区块定义

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

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

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

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

3. 加解密算法实现

3.1 安全库说明

不是操作系统或者标准化的函数库叫做第三方库.
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 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.3 整体结构回顾与区块交易示例

4.3.1 头部和身部(交易)

头部

  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.3.2 各部分具体定义

HEAD:

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

Transaction

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

INPUT:

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

OUTPUT:

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

4.3.3 区块交易实例

  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.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 说明

UNIX的理念是, 所有的沟通方式都是文件.
通信方式是以文件为基础的,是一对一的.

SOCKET是多对一的.

通过返回数字表示是否执行成功.
网络连接时, 有可能有失败, 所以发送/接受时都要判断是否成功.

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

image_1bto7u8pg1ot5qlgdi1cq71husg.png-23.9kB

  1. 系统呼叫:open(1),close(1),read(1),write(1)。
  2. 套接字socket:几乎所有经过网络的过程都经过socket。
    http://man7.org/linux/man-pages/man2/socket.2.html

    Name Purpose Man page
    AF_UNIX, AF_LOCAL Local communication unix(7)
    AF_INET IPv4 Internet protocols ip(7)
    AF_INET6 IPv6 Internet protocols ipv6(7)
    AF_IPX IPX - Novell protocols
    AF_NETLINK Kernel user interface device netlink(7)
    AF_X25 ITU-T X.25 / ISO-8208 protocol x25(7)
    AF_AX25 Amateur radio AX.25 protocol
    AF_ATMPVC Access to raw ATM PVCs
    AF_APPLETALK AppleTalk ddp(7)
    AF_PACKET Low level packet interface packet(7)
    AF_ALG Interface to kernel crypto API
    RETURN VALUE top
    On success, a file descriptor for the new socket is returned. On
    error, -1 is returned, and errno is set appropriately.

  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,目标,目标的大小)。表示是否连接成功。

send:
http://man7.org/linux/man-pages/man2/send.2.html

  1. ssize_t send(int sockfd, const void *buf, size_t len, int flags);
  2. ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
  3. const struct sockaddr *dest_addr, socklen_t addrlen);
  4. ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
  1. RETURN VALUE top
  2. On success, these calls return the number of bytes sent. On error,
  3. -1 is returned, and errno is set appropriately.

intel 小字节在前
linux 要求大在前字节

  1. address.sin_port = htons(atoi(8000))

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是udp; 普遍是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); // (2:互联网, 1:tcp, 永远都是0)
  15. if (s == -1){//s==-1,unsuccessful
  16. exit(1);
  17. }
  18. a.sin_family = 2; // 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. }

12. 计算机基础

图灵完备

图灵完备是什么意思呢?
在可计算理论中,当一组数据操作的规则(一组指令集,编程语言,或者元胞自动机)满足任意数据按照一定的顺序可以计算出结果,被称为图灵完备(turing complete)。一个有图灵完备指令集的设备被定义为通用计算机。如果是图灵完备的,它(计算机设备)有能力执行条件跳转(“if” 和 “goto”语句)以及改变内存数据。 如果某个东西展现出了图灵完备,它就有能力表现出可以模拟原始计算机,而即使最简单的计算机也能模拟出最复杂的计算机。所有的通用编程语言和现代计算机的指令集都是图灵完备的(C++ template就是图灵完备的),都能解决内存有限的问题。图灵完备的机器都被定义有无限内存,但是机器指令集却通常定义为只工作在特定的,有限数量的RAM上。

图灵不完备的语言常见原因有循环或递归受限(无法写不终止的程序,如 while(true){}; ), 无法实现类似数组或列表这样的数据结构(不能模拟纸带). 这会使能写的程序有限图灵完备可能带来坏处, 如C++的模板语言, 模板语言是在类型检查时执行, 如果编译器不加以检查,我们完全可以写出使得C++编译器陷入死循环的程序.图灵不完备也不是没有意义, 有些场景我们需要限制语言本身. 如限制循环和递归, 可以保证该语言能写的程序一定是终止的.

操作系统中字节表示

32位系统中, 标准数字用4个字节表示. 整数的范围是2的32次方.
字符串通过ASCII码来表示0-255范围内与字母等的对应.
中文字有其他的规则来对应. 例如utf8.

image_1btoa8s9oog1chl4ct1c3t24e9.png-152.3kB

Windows研发思想的来龙去脉

多进程的管理来自于UNIX

从系统的角度, 和从进程自己的角度来看内存.
程序自己的地址是连续的, 实际系统中不是连续的, 是多个程序公用内存段落.

  1. graph LR
  2. unix-->OpenVMS
  3. OpenVMS-->WindowsNT
  4. WindowsNT -->Windows2000
  5. Windows2000-->WindowsXP

UNIX --> BSD
--> SysV
---> Linux

执行程序对比

系统文件对比 执行 动态链接库 静态链接库 编译结果 源文件
windows: .exe .dll .lib .obj .c
linux: 无后缀 .so .a .o .c
  • 编译器是把非执行文件转换成执行文件。
  • .exe:直接运行程序,
  • .dll:一套函数不能运行,但可以在另一个程序运行的,更高级也可一共享,程序运行中可以引用的。
  • .lib:造一个程序可以运行,但必须重新编译才成实现,程序可以互相共享
  • .obj:链接以前的编译结果,一个程序有若干个源程序,一个源程序一个Obj文件。半成品文件编译还未处理
  • .a 是若干个 .o 组成的,.a 到 .so 需要加若干个源数据。.so是 .a加工后的。

BASE64

Base64说明:
https://baike.baidu.com/item/base64/8545775?fr=aladdin

Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045~RFC2049,上面有MIME的详细规范。
Base64编码是从二进制到字符的过程,可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码具有不可读性,需要解码后才能阅读。在MIME格式的电子邮件中,base64可以用来将binary的字节序列数据编码成ASCII字符序列构成的文本。

执行速度

TCP 接收 HTTP

以 GET, POST, PUT, DELETE, HEAD 开头.

  1. $ nc learningchain.cn 80
  2. GET / HTTP/1.1
  3. Host learningchain.cn
  4. HTTP/1.1 400 Bad Request
  5. Server: nginx/1.6.2
  6. Date: Sat, 23 Dec 2017 08:18:05 GMT
  7. Content-Type: text/html
  8. Content-Length: 172
  9. Connection: close
  10. <html>
  11. <head><title>400 Bad Request</title></head>
  12. <body bgcolor="white">
  13. <center><h1>400 Bad Request</h1></center>
  14. <hr><center>nginx/1.6.2</center>
  15. </body>
  16. </html>
  1. $ nc learningchain.cn 80
  2. GET /greet HTTP/1.1
  3. Host: learningchain.cn
  4. HTTP/1.1 200 OK
  5. Server: nginx/1.6.2
  6. Date: Sat, 23 Dec 2017 08:20:06 GMT
  7. Content-Type: text/html
  8. Transfer-Encoding: chunked
  9. Connection: keep-alive
  10. X-Powered-By: PHP/5.4.45
  11. Set-Cookie: b95a=859156495; path=/
  12. f49
  13. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  14. <html>
  15. <head>
  16. ...
  17. </html>

内存中栈与堆的区别

堆和栈的第一个区别就是申请方式不同:栈(英文名称是stack)是系统自动分配空间的,例如我们定义一个 char a;系统会自动在栈上为其开辟空间。
而堆(英文名称是heap)则是程序员根据需要自己申请的空间,例如malloc(10);开辟十个字节的空间。

由于栈上的空间是自动分配自动回收的,所以栈上的数据的生存周期只是在函数的运行过程中,运行后就释放掉,不可以再访问。
而堆上的数据只要程序员不释放空间,就一直可以访问到,不过缺点是一旦忘记释放会造成内存泄露。
从下面代码可以看出:

  1. int a = 0; //全局初始化区
  2. char *p1; //全局未初始化区
  3. main()
  4. {
  5. int b; //栈
  6. char s[] = "abc"; //栈
  7. char *p2; //栈
  8. char *p3 = "123456"; //123456\0在常量区,p3在栈上。
  9. static int c =0 //全局(静态)初始化区
  10. p1 = (char *)malloc(10); //堆
  11. p2 = (char *)malloc(20); //堆

image_1bu134etlerc8641f4g1dagglep.png-74.9kB

状态机

..

形式语言

..

stack based machine

Compilers for stack machines are simpler and quicker to build than compilers for other machines. Code generation is trivial and independent of prior or subsequent code. For example, given an expression x+y*z+u, the corresponding syntax tree would be:

image_1bv3kbvvj4uf12u31ata1avc1n8f1g.png-33.9kB

The compiled code for a simple stack machine would take the form:

  1. push x
  2. push y
  3. push z
  4. multiply
  5. add
  6. push u
  7. add

逆波兰表达式

Reverse Polish Notation
逆波兰表达式,它的语法规定,表达式必须以逆波兰表达式的方式给出。逆波兰表达式又叫做后缀表达式。
可以将复杂表达式转换为可以依靠简单的操作得到计算结果的表达式。例如(a+b)(c+d)转换为ab+cd+
它的优势在于只用两种简单操作,入栈和出栈就可以搞定任何普通表达式的运算。其运算方式如下:
如果当前字符为变量或者为数字,则压栈,如果是运算符,则将栈顶两个元素弹出作相应运算,结果再入栈,最后当表达式扫描完后,栈里的就是结果。
在数据结构和编译原理这两门课程中都有介绍,下面是一些例子:

4 * ( A + B) 的堆栈变化过程示意:
image_1bv3bj49g17661el1ql71heauap9.png-10.1kB
(6*(4+5) - 25 )/(2+3) 的例子的二叉树表示:
image_1bv3cqt0g1n611dr21l6ms6k1t0j1g.png-59.3kB
3*4+5*6 = 42 的整个计算过程图示:
image_1bv3bpor7s2rlma19dl1id5dn913.png-382.2kB
12 * ( 3 + 4 ) - 6 + ( 8 / 2 ) = 82 的运算过程图示:
image_1bv3d1c4s1aij1s71uvn437m2t9.png-17.2kB

正常的表达式 ---> 逆波兰表达式
a+b ---> a,b,+
a+(b-c) ---> a,b,c,-,+
a+(b-c)*d ---> a,b,c,-,d,*,+
a+d*(b-c)--->a,d,b,c,-,*,+
a=1+3 ---> a=1,3 +
http=(smtp+http+telnet)/1024 写成什么呢?
http,smtp,http,+,telnet,+,1024,/,=

Postfix evaluation algorithm

  1. for each token in the postfix expression:
  2. if token is an operator:
  3. operand_2 pop from the stack
  4. operand_1 pop from the stack
  5. result evaluate token with operand_1 and operand_2
  6. push result back onto the stack
  7. else if token is an operand:
  8. push token onto the stack
  9. result pop from the stack

13. Linux相关说明

Linux没有官方的文档, gnu的有一些文档.

可以认为可信的"官方"文档:
https://www.kernel.org/doc/man-pages/
http://www.man7.org/
https://linux.die.net/

13.1 基础操作

设置文本编译器

  1. alias nano = "nano -w -x -E -T 3 -I -S"

16进制展示与xxd

xxd 可用来查看生字节的16进制展示.

以下是个示例.
每行16个字节. 每4个字母数字为2个字节.

  1. $ xxd 1.block
  2. 0000000: 196f d33e b38e 61d5 4579 d98e 16d1 ac4e .o.>..a.Ey.....N
  3. 0000010: 279e 065c 07d7 5461 42b7 fe60 d226 72bc '..\..TaB..`.&r.
  4. 0000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................
  5. 0000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................
  6. 0000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................
  7. 0000050: 0000 0000 0000 0000 0000 0000 0000 0000 ................

字节的计算过程:
e8 : 232
e803 = 232 + 256 *3 = 1000
图中所示, 前2个字节表示整数1000

  1. 00000e0: e803 0000 0000 0000 0000 0000 0000 0000 ................

linux终端共享使用说明

作共享屏幕:

  1. tmux -S $SOCKET new -t $SESSION

接入共享屏幕

  1. tmux -S $SOCKET attach -t $SESSION -r

-r 参数表示只读, 去掉可以一起写.

示例:

  1. tmux -S /tmp/330 attach -t 0 -r
  2. or
  3. sh /tmp/a

linux 传统安装

linux来源于unix的传统, 安装时会将不同的文件如设置,执行,变量会放在不同的路径

13.2 编译执行相关

程序运行过程

head |... |... |... |... |... |
section

_start()
initialize libc.so
run main()
libc.so and system call are heavily dependedt up global variables(全局变量)
argc argv envp

对于复杂的命令行参数,需要parser,analyzer来分析. 简单起见,也可以把顺序等写死.

./bitcoind --help
conciseCoin
./ccn -k yuanxun.private -s /tmp/blocks
argv1 argv2 argv3

image_1buksdg4vk6r1ddd1eo266n1aek9.png-96.5kB
命令行参数argc 与argv 在内存中的图示:
image_1bukrl5tp1gbi108018po15cc1vbs9.png-104.2kB

编译执行源代码:

  1. tcc -c program.c -o program.o
  2. tcc -o program.elf program.o libtfm.a libtomcrypt.a
  3. ./program.elf

注意: 编译时文件名的顺序不要变, 否则无法编译通过.

查看库

  1. 查看库的函数名
  2. $ readelf -S libtomcrypt.a | grep File
  3. File: libtomcrypt.a(aes.o)
  4. File: libtomcrypt.a(aes_enc.o)
  5. File: libtomcrypt.a(anubis.o)
  6. File: libtomcrypt.a(blowfish.o)
  7. File: libtomcrypt.a(camellia.o)
  8. File: libtomcrypt.a(cast5.o)
  9. File: libtomcrypt.a(des.o)

网络TCP/UDP发送与监听工具 nc

多进程多线程

  1. multiprocess 多进程
  2. multithread 多线程
  3. poll/select

symmetric asymmetric

如果一个应用程序去处理多个设备,例如应用程序读取网路数据,按键,串口,一般能想到的有三种方法:
方法1:
串行+阻塞的方式读取:
while(1) {
read(标准输入);
read(网络);
}
缺点:每当阻塞读取标准输入时,如果用户不进行标准输入的操作,而此时客户端给服务器发送数据,导致服务器无法读取客户端发送来的数据!

方法2:
采用多线程或者多进程机制来实现读取:
开辟多个线程,每一个线程处理一个设备,不会导致的数据的无法读取,但是系统的开销相比方法1要大!

方案3:采用linux系统提供的高级IO的处理机制
select/poll:两者一样,主进程能够利用select或者poll能够对多个设备进行监听!

14. 程序开发语言相关说明

14.1 C语言

14.1.1 C语言基础

  1. #include "stdio.h" 包含输入和输出相关的函数 printf() fopne() fread() fwrite() fclose()
  2. #include "stdlib.h" 包含内存管理的函数 malloc() free()
  3. #include "string.h" 包含字符串处理的函数 strlen() strtok() strcpy()
  4. #include "sys/socket.h" 包含套接字的函数
  5. #include "arpa/inet.h" 互联网套接字函数

14.1.2 注意点

构造8字节, 64位的数字处理

32位的机器, 要想创造64位的整数,
C语言里long long int 会分配一个64位的整数.
用特定的函数来支持. 编译器支持. 虽然机器本身不支持.

  1. unsigned char *y;
  2. unsiged int z;
  3. y = malloc(8); // 分配8个字节
  4. z = 1000; // 4个字节的变量z
  5. memcpy(y, &z, 4); // 把 4个字节的z 复制到 y上.
  6. memset(y + 4, 0, 4); // 后4个字节补充0.

memset与填充0

buffer 在创造时( malloc() ), 不会自动地填充成0. 所以可以用memset.

  1. buffer = malloc(1000);
  2. memset(buffer,0,1000);

void 指针

课上bug已解,原因是C语言不能从void类型的指针中取值,需要进行两次强转,形式如下:

  1. while ((int)list != 0 ) {
  2. data = (unsigned char *) *((int *) list);
  3. printf("value: %d%c", (int)data, 10);
  4. list = (void *)*((int *) (list + 4));
  5. printf("list: %d%c", (int)list, 10);
  6. }

包含本身长度的字符串.

字符串分2种,
一种是\0结尾, 不记录长度. 不能存\0, 叫做非正当字符串 improper (c string)
一种记录长度, 可以存任意字符串. 叫做正当字符串 proper (pascal string)
其中int整数存储长度, 本身占用4个字节.
下面是后一种

构造包含自己长度的字符串, [length,string_content]

文件结束符

当公钥存在一个文件里.
文件里可能会增加一个跳行. 引起base64的函数转变的崩溃. 因为base64没有跳行字符.
最好是拿之前的函数来读文件, 判断最后一个字符是不是10, 若是10要去掉. 倒数第二个是10也要删掉.
或者把 钥匙 放在代码变量里.

signed char 与 unsigned char区别

signed char取值范围是 -128 到 127(有符号位)
unsigned char 取值范围是 0 到 255
char 到底是signed char还是unsigned char?这得看编译器.

  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. signed char a = -1;
  5. unsigned char b = -1;
  6. printf("%%d:\n");
  7. printf("signed: %d\n", a);
  8. printf("unsiged:%d\n", b);
  9. printf("%%u:\n");
  10. printf("signed: %u\n", a);
  11. printf("unsigned: %u\n", b);
  12. }
  1. %d:
  2. signed: -1
  3. unsiged:255
  4. %u:
  5. signed: 4294967295
  6. unsigned: 255

uint8_t uint_16_t uint32_t uint64_t

这些数据类型是 C99 中定义的,具体定义在:/usr/include/stdint.h

  1. //ISO C99: 7.18 Integer types <stdint.h>
  2. typedef signed char int8_t;
  3. typedef short int int16_t;
  4. typedef int int32_t;
  5. # if __WORDSIZE == 64
  6. typedef long int int64_t;

一般来说整形对应的*_t类型为:
uint8_t为1字节
uint16_t为2字节
uint32_t为4字节
uint64_t为8字节
1. 这些类型的来源:这些数据类型中都带有_t, _t 表示这些数据类型是通过typedef定义的,而不是新的数据类型。
2. 在涉及到跨平台时,不同的平台会有不同的字长,所以利用预编译和typedef可以方便的维护代码。
3. 在C99标准中定义了这些数据类型,具体定义在:/usr/include/stdint.h ISO C99: 7.18 Integer types

14.2 php语言

函数说明

ord()

把字母转成字节

hash

string hash ( string data [, bool $raw_output = false ] )

  1. 参数
  2. algo
  3. 要使用的哈希算法,例如:"md5""sha256""haval160,4" 等。
  4. data
  5. 要进行哈希运算的消息。
  6. raw_output
  7. 设置为 TRUE 输出原始二进制数据, 设置为 FALSE 输出小写 16 进制字符串。
  8. 返回值
  9. 如果 raw_output 设置为 TRUE 则返回原始二进制数据表示的信息摘要, 否则返回 16 进制小写字符串格式表示的信息摘要。

http://php.net/manual/zh/function.hash.php

array_push()

将一个或多个单元压入数组的末尾(入栈)

  1. $a=array("Dog","Cat");
  2. array_push($a,"Horse","Bird");//内容加到数组中
  3. print_r($a);

输出:

  1. Array
  2. (
  3. [0] => Dog
  4. [1] => Cat
  5. [2] => Horse
  6. [3] => Bird
  7. )

array_shift()

将数组开头的单元移出数组
另外, array_unshift()在数组开头插入一个或多个单元

  1. $stack = array("Java", "Php", "C++", "C#", "Ruby");
  2. array_shift($stack);
  3. print_r($stack);
  1. Array
  2. (
  3. [0] => Php
  4. [1] => C++
  5. [2] => C#
  6. [3] => Ruby
  7. )

15. 密码学相关说明

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

image_1btobo6mh1cpr16ui1lvo3erlvj1g.png-39kB

hash的应用

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

image_1btobljiu1bq0i1t1q3c1g5l12tn13.png-155.3kB

椭圆曲线

ECDSA 签名,
相比RSA
a. 起确权作用, 这笔交易是我发起的.
b. 更高效,
c. 快.

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

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

应用

多种签名,

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
https://github.com/anders94/public-private-key-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/

Blockchain Technology Explained (2 Hour Course)
https://www.youtube.com/watch?v=qOVAbKKSH10

详解比特币的原理和运行机制
http://open.163.com/movie/2016/7/I/S/MBQU8RAT9_MBQU9CUIS.html

视频介绍:
https://www.youtube.com/watch?v=bBC-nXj3Ng4
https://www.youtube.com/watch?v=ssbDtvY3xCs
https://www.youtube.com/watch?v=jKYhLpHJv8U

比特币和数字货币技术-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
Design of Unix

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

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