从零开始Python区块链搭建(一)

python实现简易区块链 python实现山寨比特币交易系统 阅读详情

三分钟区块链笔记#

区块链搭建(一)

环境:Python

前言

0

这篇文章是我根据b站搜到的教学视频,总结出来自己的第一篇关于如何用Python搭建区块链的笔记,是我从理论向实践迈出的重要一步吧。目前这篇文章并没有涉及区块链的所有内容,并且仅涉及到在本地软件中一些类区块链功能的实现。不过这些功能的实现,是为以后真正搭建出自己的区块链而作的准备~

本篇文章涉及的内容,均来自b站up主AsianWhale上传的视频**《[教程向]手把手Python搭建区块链》****,BV号为BV1Hb411c7oH。**感兴趣的小伙伴可以去学习哦!

本篇文章的代码非原创,均来自上述视频中的内容。

本来是向做“三分钟Fintech笔记”的,但是篇幅确实写得有点长了······下次会注意的!orz

菜单

1

在进行区块链搭建之前,首先我们先要列出本篇文章所需要实现的区块链功能,分别是:

(1)创建一个交易

(2)挖一个区块

(3)查看区块链中的所有区块

(4)查看区块链中所有的参与者

(5)验证交易有效性

(6)验证区块链的有效性

菜菜认为先从宏观的层面把握,要比一个一个函数开始看起会更好一些,我们首先给出本地命令的菜单,这个菜单涉及了这篇文章涉及到的所有要实现的区块链功能,我们可以通过输入:1、2、3···的指令来选择我们要进行的操作,代码如下:

(秀米排版代码制表符有问题,请尽量不要直接复制粘贴,否则会报错invalid character in identifier)


while waiting_for_input:
    print('Please choose')
    print('1: Add a new transaction value')
    print('2: Mine a new block')
    print('3: Output the blockchain blocks')
    print('4: Output participants')
    print('5: Check transaction validity')
    print('h: Manipulate the chain')  # Manipulate 篡改
    print('q: Quit')
    get_user_choice = input('Please choose your act:')
    user_choice = get_user_choice
    if user_choice == '1':
        pass
    elif user_choice == '2':
        pass
    elif user_choice == '3':
        pass
    elif user_choice == '4':
        pass
    elif user_choice == '5':
        pass
    elif user_choice == 'h':
        pass
    elif user_choice == 'q':
        print('User left!')
        break

定义函数

2

一、创建一个交易

首先,我们知道一个最简单的交易包含了付款方、收款方和交易金额。此处我们暂时只考虑这三个变量,分别将其定义为sender、recipient、amount,于是:

注意最后几行的if语句,是对第一部分提到的菜单条件语句的修改,无法单独运行,后面同理。

# 定义全局变量
open_transaction = []
owner = 'Passer'
participants = {'Passer'} # 名字可以自定义

def get_transaction_value():
    ''' Return the input of recipient and amount '''
    tx_recipient = input('Enter the recipient of the transaction:')
    tx_amount = float(input('Your transaction amount please:'))
    return tx_recipient, tx_amount

def add_transaction(recipient, sender=owner, amount=1.0):
    ''' Append a new transaction to the list of open_transaction'''
    transaction = {
        'sender':sender,
        'recipient':recipient,
        'amount':amount
    }
    open_transaction.append(transaction)
    participants.add(sender)
    participants.add(recipient)
    return True
    
    # 此处对菜单部分进行修改,单独无法运行
    if user_choice == '1':
        tx_data = get_transaction_value()
        recipient, amount = tx_data
        # Add transaciton amount to the blockchain
        if add_transa
用Python从零开始创建区块链_基于python做区块链 ”"简单的工作量证明:- 查找一个 p’ 使得 hash(pp’) 以4个0开头- p 是上一个块的证明, p’ 是当前的证明:return:“”"proof = 0proof += 1“”"验证证明: 是否hash(last_proof, proof)以4个0开头?“”" 阅读详情

相关推荐

如何用Python从零开始创建区块链

我们知道区块链是由区块的记录构成的不可变、有序的链结构,记录可以是交易、文件或任何你想要的数据,重要的是它们是通过哈希值(hashes)链接起来的。到这里,区块链的概念就清楚了,每个新的区块都包含上一个区块的Hash,这是关键的一点,它保障了区块链不可变性。前面提到,冲突是指不同的节点拥有不同的链,为了解决这个问题,规定最长的、有效的链才是最终的链,换句话说,网络中有效最长链才是实际的链。方法向列表中添加一个交易记录,并返回该记录将被添加到的区块(下一个待挖掘的区块)的索引,等下在用户提交交易时会有用。

HongYingClub-优快云 1343

走进区块链(一):用Python实现第一个区块链小程序

源代码链接:https://github.com/dvf/blockchain 大家好!这是本人踩在巨人的肩膀上,实现的第一个区块链小程序。在实现代码的过程中,我遇到了很多问题,不过,幸好都解决了。在这里,我会尽可能的将操作步骤写得更详细。接下来,让我们一起走进区块链吧! 一、初识区块链 区块链是由不可变的、有顺序记录的区块组成。他们可以包含交易数据、文件数据或者其他你想要记录的数据。不...

每天向前一小步 2935

区块链学习2——区块链浏览器的搭建

1.环境准备 一键部署模式,采用的是同机部署。 Javajdk1.8.0_121及以上版本 Python 2.7 MySQL-Python 1.2.5 数据库mysql-5.6及以上版本 官方文档一键部署说明:https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/browser/deploy.html#id17 (1)Java环境搭建:在搭建控制台的时候已经安装了Java环境,使用以下命令查看Java版本。 j..

wwy的博客 1万+

教你使用Python从零开始搭建一个区块链项目!

你是否会和我一样,对加密数字货币底层的区块链技术非常感兴趣,特别想了解他们的运行机制。 但是学习区块链技术并非一帆风顺,我看多了大量的视频教程还有各种课程,最终的感觉就是真正可用的实战课程太少。 我喜欢在实践中学习,尤其喜欢以代码为基础去了解整个工作机制。如果你我一样喜欢这种学习方式,当你学完本教程时,你将会知道区块链技术是如何工作的。 写在开始之前 记住,区块链是一个不可变的、有序的...

PythonJavaPHP的博客 844

Python语言的区块链

在深入探讨Python与区块链的结合之前,我们首先需要了解区块链的基本概念。区块链是一种去中心化的数据存储技术,其由一系列的区块(block)以线性序列连接而成。每个区块中包含了一部分数据、时间戳以及指向前一个区块的哈希值(hash)。Python是一种高级编程语言,因其简单易读的语法和丰富的库而受到广泛欢迎。自从发布以来,Python成功地应用于数据科学、人工智能、网络开发等多个领域。对于区块链开发而言,Python也有其独特的优势。

2501_90426009的博客 1953

Python入门实战:区块链应用开发

1.背景介绍 区块链(Blockchain)是一个分布式数据库系统。它是一组去中心化的、基于区块技术的数据记录系统。区块链可以说是一种全新的技术,具有独特的特征,例如:数据不重复、分布式记账、不可伪造、匿名性、共识机制等。目前已经有越来越多的公司和个人开始采用区块链技术,比如人民币数字货币的白皮书中就提到:“区块链技术将会成为下一个互联网基础设施”。那

AI天才研究院 366

从零开始:快速搭建一条区块链的完整教程( Python语言版)

通过以上步骤,你已经成功搭建了一条简单的区块链。区块链技术拥有广泛的应用场景,虽然本文只是实现了一个基础的区块链系统,但它为你进一步深入学习区块链技术奠定了基础。希望这篇教程对你有所帮助!

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1373

构建可编程记忆系统:OpenClaw-SuperMemory本地部署与智能知识管理实战

在信息过载的时代,高效的知识管理与智能检索成为技术从业者的核心需求。向量数据库与嵌入模型技术通过将文本转化为高维向量,实现了基于语义相似度的智能搜索,突破了传统关键词匹配的局限。这项技术的核心价值在于将静态存储的信息转化为可动态查询和计算的知识资产,极大地提升了信息调用的准确性和效率。其应用场景广泛,从个人笔记管理、对话历史归档到企业知识库构建都能发挥关键作用。本文聚焦于开源项目OpenClaw-SuperMemory,它正是基于这一技术栈,通过本地化部署实现了可编程记忆系统的构建。项目集成了ChromaD

weixin_42525482的博客 321

从零解析特斯拉线圈:谐振变压器的核心原理与DIY实践

本文深入解析特斯拉线圈的工作原理与DIY实践,从LC振荡电路到电磁耦合,详细介绍了谐振变压器的核心原理。通过材料清单、绕制技巧和安全指南,帮助爱好者从零开始打造迷你闪电发生器,体验高压电子实验的独特魅力。

weixin_33670786的博客 494

钢铁雄心4存档修改全攻略:从基础设置到高级玩法(附国家代码表)

本文详细解析《钢铁雄心4》存档修改技巧,从基础设置到高级玩法全覆盖。包括存档文件位置、格式转换、国家实力调整、国际关系修改等实用内容,并附赠国家代码表。掌握存档修改技能,解锁游戏全部潜力,实现精细参数控制,超越控制台指令的局限。

weixin_29233857的博客 1439

天线学习笔记——HFSS简单阵列天线

在HFSS15.0版本中使用 Radiation --> Antenna Array Setup 设置天线阵列的参数时的设计列表如下: 值得注意的是,在该版本中所定义的是:第一个阵元的位置坐标(First Cell Position)、阵元之间的间距(Directions)和阵元的数量(Number of Cells) 这些参数。 在ANSYS中的HFSS仿真中定义天线阵列如下: 与老版本不同的是:中心点坐标(Center Position)和布局设置(Layout Setting)。在布局设置中

Ethan的博客 1万+

android 数据库锁的问题

最近在项目中遇到一个错误: 12-26 17:29:10.501 32592 32644 W SQLiteConnectionPool: The connection pool for database '***.db' has been unable to grant a connection to thread 1378 (thread-pool-0) with flags 0x2 for...

低调的成长 2905

Pattern Recognition 投稿过程记录,含Elsevier Latex模板使用

Pattern Recognition 投稿过程记录,含Elsevier Latex模板使用 最近在Pattern Recognition投出了一个文章,纯纯属于是第一次投稿,感觉自己写了一坨屎,事实是这确实也是一坨屎,现在是投了之后在等待一个拒稿的状态。 但是还是记录一下一些流程 1. 下载模板 在出版商Elsevier的栏目里有对于稿件的结构要求,也提供了Latex模板。同时,也给作者提供了Guides, 可以仔细阅读。下面这个连接咱们可以下载到Guides以及看到一些文章的要求。 https://ww

weixin_44153180的博客 3万+

optee系统启动流程

BL2 - Trusted Boot Firmware,一般为Trusted Bootloader, 也称第一个启动镜像。BL31 - EL3 Runtime Firmware,负责双系统切换,运行在secure monitor 或ATF中。BL33 - Non-Trusted Firmware,一般为uboot、linux kernel。BL32 - Secure-EL1 Payload, 一般为TEE OS Image。BL1 - Trusted ROM,一般为BootRom。

baron-周贺贺-代码改变世界ctw 279

保研考研机试攻略:python笔记(4)

保研考研机试攻略:python笔记(4)二分法+最大公约数+最小公倍数+素数判断+幂次方mod方法+匹配问题+哈希算法+哈夫曼编码+二叉树

qq_63349644的博客 1097

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

上一篇: 用Python实现基于区块链技术的投票系统
下一篇: 通过 web3.py 用 Python 存取 Ethereum
Python_P叔
博客等级 码龄3年 5454粉丝 827原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值