本文是几个教程的更新和融合,一部分通过python实现展示简单的区块链结构和过程,一部分用truffle发布简单的solidity智能合约脚本,算是区块链入门(不算吧。。)
python区块链模拟脚本(本地)
环境 :
3.7 python
win10
import hashlib
# class Block:
# def __init__(self, data, prev_hash):
# self.previous_hash = prev_hash
# self.data = data
#
# # calculate hash
# @property
# def hash(self):
# message = hashlib.sha256()
# message.update(str(self.data).encode('utf-8'))
# return message.hexdigest()
class Block():
""""
"""
def __init__(self,data,prev_hash):
self.previous_hash = prev_hash
self.data = data
self.nonce = ""
@property
def hash(self):
message = hashlib.sha256()
message.update(str(self.data).encode('utf-8'))
message.update(str(self.nonce).encode('utf-8'))
digest = message.hexdigest()
return digest
# first Block making function
# def create_genesis_block():
# return Block(data="Genesis Block", prev_hash="")
def create_genesis_block():
block = Block(data="Genesis Block",prev_hash="")
pow = ProofOfWork(block)
nonce, digest = pow.mine()
print("nonce: " + str(nonce))
print("digest: " + str(digest))
return block
class BlockChain():
def __init__(self):
self.blocks = [create_genesis_block()]
def add_block(self,data):
prev_block = self.blocks[len(self.blocks)-1]
block = Block(data, prev_block.hash)
pow = ProofOfWork(block)
nonce, digest = pow.mine()
block.nonce = nonce
self.blocks.append(block)
# class BlockChain():
# """docstring for BlockChain"""
#
# def __init__(self):
# self.blocks = [create_genesis_block()]
#
# def add_block(self, data):
# prev_block = self.blocks[len(self.blocks) - 1]
# new_block = Block(data, prev_block.hash)
# self.blocks.append(new_block)
# return new_block
# if __name__ == '__main__':
# bc = BlockChain()
#
# b1 = bc.add_block["jack send 0.3 btc to Alice"]
# b2 = bc.add_block["Alice send 0.1 btc to Tom"]
#
# for b in bc.blocks:
# print("Prev Hash:{}".format(b.previous_hash))
# print("Data:{}".format(b.data))
# print("Hash:{}".format(b.hash))
# print("\n")
class ProofOfWork():
def __init__(self,block):
self.block = block
#mining
def mine(self):
# 这次要让挖出的散列值开头4个0
prefix = '0000'
i = 0
while True:
nonce = str(i)
message = hashlib.sha256()
# 被散列化处理的内容,包括数据和nonce(随机数)
message.update(str(self.block.data).encode('utf-8'))
message.update(nonce.encode('utf-8'))
digest = message.hexdigest()
if digest.startswith(prefix):
return nonce,digest
i += 1
bc = BlockChain()
b1 = bc.add_block("jack send 0.3 btc to Alice")
b2 = bc.add_block("Alice send 0.1 btc to Tom")
for b in bc.blocks:
print("Prev Hash:{}".format(b.previous_hash))
print("Data:{}".format(b.data))
print("Hash:{}".format(b.hash))
print("\n")
truffle的solidity发布到ganathe模拟的以太网
- Ganathe和truffle 安装和连接
- 参考:
https://www.bilibili.com/video/BV1ds41177Cy?p=5
内容更新:
1.新建项目命令改为 truffle init(原文看到叫创建truffle就不用看了)
2.metamask (视频教程出现,检测用,已经有点老了)连接RPC网络时现在要chainId了,对应的测试链ID为1337(国内居然每一个论坛说过艹),参考连接:https://github.com/MetaMask/metamask-extension/issues/9683 - truffle的使用和第一个solidity文件
改为以下solidity脚本
pragma solidity >=0.5.6<0.7.0;
contract HelloWorld {
constructor() public{
}
function sayHello () pure public returns(string memory) {
return ("Hello World");
}
function print(string memory name) pure public returns (string memory) {
return name;
}
}
并且注意!!! 用truffle init 命令创建的 1_initial_migration.js 文件需要改成如下:
const Migrations = artifacts.require("Migrations");
const HelloWorld = artifacts.require("HelloWorld");
module.exports = function (deployer) {
deployer.deploy(Migrations);
deployer.deploy(HelloWorld);
};
不要改成var和.sol,太老了已经不能用了
并且并且注意!!!!
win的参数文件只有truffle-config,其中的networks和其下的development只需要取消注销就行,参数具体如下
networks: {
// Useful for testing. The `development` name is special - truffle uses it by default
// if it's defined here and no other network is specified at the command line.
// You should run a client (like ganache-cli, geth or parity) in a separate terminal
// tab if you use this network and you must also set the `host`, `port` and `network_id`
// options below to some value.
//
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 7545, // Standard Ethereum port (default: none)
network_id: "*", // Any network (default: none)
},
其余的基本按照上面链接的教程即可,测试过可以跑了
以上
may the flame guide thee