golang[47]-区块链-比特币交易

栏目: Go · 发布时间: 7年前

内容简介:第一笔交易比较特殊,他是coinbase交易,矿工的收益。金额每4年减少一半,从2009年一开始一个区块奖励50BTC、后来减少为了25个BTC、一直到18年 12.5BTC。总共有2100万BTC。交易和我们的银行的转账非常不同,比特币中没有记录账户的信息、而是交易的信息。

比特币的交易

第一笔交易比较特殊,他是coinbase交易,矿工的收益。

金额每4年减少一半,从2009年一开始一个区块奖励50BTC、后来减少为了25个BTC、一直到18年 12.5BTC。总共有2100万BTC。

交易和我们的银行的转账非常不同,比特币中没有记录账户的信息、而是交易的信息。

go实现交易 demo

package main

import (
	"bytes"
	"encoding/gob"
	"log"
	"crypto/sha256"
	"fmt"
	"strings"
)
const subsidy = 100
type Transation struct{
	ID []byte
	Vin []TXInput
	Vout []TXOutput

}


 type TXInput struct {
 	TXid []byte
 	Voutindex int
 	Signature []byte
 }

type TXOutput struct {
	value int
	PubkeyHash []byte
}

//格式化打印交易完整信息
func (tx Transation) String() string {
	var lines []string

	lines = append(lines, fmt.Sprintf("--- Transaction %x:", tx.ID))

	for i, input := range tx.Vin {
		lines = append(lines, fmt.Sprintf("     Input %d:", i))
		lines = append(lines, fmt.Sprintf("       TXID:      %x", input.TXid))
		lines = append(lines, fmt.Sprintf("       Out:       %d", input.Voutindex))
		lines = append(lines, fmt.Sprintf("       Signature: %x", input.Signature))
	}

	for i, output := range tx.Vout {
		lines = append(lines, fmt.Sprintf("     Output %d:", i))
		lines = append(lines, fmt.Sprintf("       Value:  %d", output.value))
		lines = append(lines, fmt.Sprintf("       Script: %x", output.PubkeyHash))
	}

	return strings.Join(lines, "\n")
}


//序列化
func (tx Transation) Serialize() []byte{
	var encoded bytes.Buffer
	enc:= gob.NewEncoder(&encoded)

	 err:= enc.Encode(tx)

	 if err!=nil{
	 	log.Panic(err)
	 }
	 return encoded.Bytes()
}
//计算交易的hash值
func (tx *Transation) Hash() []byte{

	txcopy := *tx
	txcopy.ID = []byte{}

	hash:= sha256.Sum256(txcopy.Serialize())

	return hash[:]
}

//根据金额与地址新建一个输出
func NewTXOutput(value int,address string) * TXOutput{
	  txo := &TXOutput{value,nil}
	  txo.PubkeyHash = []byte(address)
	  return txo
}



//第一笔coinbase交易
func NewCoinbaseTX(to string) *Transation{
	txin := TXInput{[]byte{},-1,nil}
	txout := NewTXOutput(subsidy,to)

	tx:= Transation{nil,[]TXInput{txin},[]TXOutput{*txout}}

	tx.ID = tx.Hash()

	return &tx
}




func main(){
	newTX := NewCoinbaseTX("jonson")
	fmt.Printf("%s",newTX.String())

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

CSS那些事儿

CSS那些事儿

林小志 / 电子工业出版社 / 2009-10 / 49.80元

本书专注于CSS技巧实例的讲解,由浅入深地分析了CSS样式在布局时所需要理解的原理。放弃到处可见的基础知识、网络中能随意搜索到的hack技巧,侧重原理分析,拓展读者使用CSS布局的思维方式,通过本书的阅读读者将会了解到使用CSS布局的强大功能。 全书以传达CSS布局思维为中心,通过页面中的文字、图片、表格、表单等常见元素的处理及各种页面布局方式的使用,使读者能深入了解到如何在页面中更好地运用......一起来看看 《CSS那些事儿》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具