Skip to content

Commit dabb9d7

Browse files
committed
add transcation
1 parent 4021c58 commit dabb9d7

18 files changed

+844
-211
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.idea
22
*.db
3-
go-blockchain
3+
go-blockchain
4+
*.dat

README.md

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,74 @@
11
# go-blockchain
22

3-
**创建账号:**
3+
**创建钱包**
44

55
```
6-
./go-blockchain createblockchain -address Ivan
6+
> ./go-blockchain createwallet
7+
> Your new address: 1321QKXdSdYXLPZiGxC9NS6HjTuDEFR119
8+
> ./go-blockchain createwallet
9+
> Your new address: 1546AtPEFt5uGyvhbRDLUoqLTy5zfUZhsY
10+
```
11+
12+
**创建区块链:**
13+
14+
```
15+
> ./go-blockchain createblockchain -address 1321QKXdSdYXLPZiGxC9NS6HjTuDEFR119
16+
> 000000a69db5326fa6037956b4cfef0ecdc029b3de3ddad59bf0940944653510
17+
>
18+
> Done!
719
```
820

921
**查看账号余额:**
1022

1123
```
12-
./go-blockchain getbalance -address Ivan
24+
> ./go-blockchain getbalance -address 1321QKXdSdYXLPZiGxC9NS6HjTuDEFR119
25+
> Balance of '1321QKXdSdYXLPZiGxC9NS6HjTuDEFR119': 10
1326
```
1427

1528
**转账:**
1629

1730
```
18-
./go-blockchain send -from Ivan -to Pedro -amount 6
31+
> ./go-blockchain send -from 1321QKXdSdYXLPZiGxC9NS6HjTuDEFR119 -to 1546AtPEFt5uGyvhbRDLUoqLTy5zfUZhsY -amount 1
32+
> 00000013eda8154a87b0ee7ad5bf54f63cd6a0a2de89ce4bbc9f08313cf2c62a
33+
>
34+
> Success!
1935
```
2036

2137
**打印区块链:**
2238

2339
```
24-
./go-blockchain printchain
25-
```
40+
> ./go-blockchain printchain
41+
> ============ Block 00000013eda8154a87b0ee7ad5bf54f63cd6a0a2de89ce4bbc9f08313cf2c62a ============
42+
> Prev. block: 000000a69db5326fa6037956b4cfef0ecdc029b3de3ddad59bf0940944653510
43+
> PoW: true
44+
>
45+
> --- Transaction d3c67d1911c64c6287c9eafabbd3c6787a512cbf54bd44eb3dfe0edb259ef46c:
46+
> Input 0:
47+
> TXID: a90fa883b56fad4b2dc0bb2c50a4c78430b1ac0bef5d3cd62cf836a2878e0a9a
48+
> Out: 0
49+
> Signature: cf16e093bace5b843edef1e272f9cdabd47b741265c4c3a2e651ab6f3c2a466d396621df57bd48d09bce686962e7b34ca66c83e5bb6ca4c4204661d488fe532b
50+
> PubKey: a09f43b8c60eef9f511cb8ac2e79c2a6ed8cc6c8bae3ad4f71046538094ecff297fd6df23a6f3f2b6a0345594043bfe65e1e671efdf68a5e06acfc24141f65df
51+
> Output 0:
52+
> Value: 1
53+
> Script: 2c76112cf3bcf8514978b97055563f92fdb3b966
54+
> Output 1:
55+
> Value: 9
56+
> Script: 162100ce8ca041f88ad7089aa0b06a99862a2969
57+
>
58+
>
59+
> ============ Block 000000a69db5326fa6037956b4cfef0ecdc029b3de3ddad59bf0940944653510 ============
60+
> Prev. block:
61+
> PoW: true
62+
>
63+
> --- Transaction a90fa883b56fad4b2dc0bb2c50a4c78430b1ac0bef5d3cd62cf836a2878e0a9a:
64+
> Input 0:
65+
> TXID:
66+
> Out: -1
67+
> Signature:
68+
> PubKey: 5468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73
69+
> Output 0:
70+
> Value: 10
71+
> Script: 162100ce8ca041f88ad7089aa0b06a99862a2969
72+
```
73+
74+

cli/cli.go

Lines changed: 39 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,38 @@ package cli
33
import (
44
"flag"
55
"fmt"
6-
"github.com/sasaxie/go-blockchain/core"
76
"log"
87
"os"
9-
"strconv"
108
)
119

10+
// CLI responsible for processing command line arguments
1211
type CLI struct{}
1312

13+
func (cli *CLI) printUsage() {
14+
fmt.Println("Usage:")
15+
fmt.Println(" createblockchain -address ADDRESS - Create a blockchain and send genesis block reward to ADDRESS")
16+
fmt.Println(" createwallet - Generates a new key-pair and saves it into the wallet file")
17+
fmt.Println(" getbalance -address ADDRESS - Get balance of ADDRESS")
18+
fmt.Println(" listaddresses - Lists all addresses from the wallet file")
19+
fmt.Println(" printchain - Print all the blocks of the blockchain")
20+
fmt.Println(" send -from FROM -to TO -amount AMOUNT - Send AMOUNT of coins from FROM address to TO")
21+
}
22+
23+
func (cli *CLI) validateArgs() {
24+
if len(os.Args) < 2 {
25+
cli.printUsage()
26+
os.Exit(1)
27+
}
28+
}
29+
30+
// Run parses command line arguments and processes commands
1431
func (cli *CLI) Run() {
1532
cli.validateArgs()
1633

1734
getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError)
1835
createBlockchainCmd := flag.NewFlagSet("createblockchain", flag.ExitOnError)
36+
createWalletCmd := flag.NewFlagSet("createwallet", flag.ExitOnError)
37+
listAddressesCmd := flag.NewFlagSet("listaddresses", flag.ExitOnError)
1938
sendCmd := flag.NewFlagSet("send", flag.ExitOnError)
2039
printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError)
2140

@@ -36,6 +55,16 @@ func (cli *CLI) Run() {
3655
if err != nil {
3756
log.Panic(err)
3857
}
58+
case "createwallet":
59+
err := createWalletCmd.Parse(os.Args[2:])
60+
if err != nil {
61+
log.Panic(err)
62+
}
63+
case "listaddresses":
64+
err := listAddressesCmd.Parse(os.Args[2:])
65+
if err != nil {
66+
log.Panic(err)
67+
}
3968
case "printchain":
4069
err := printChainCmd.Parse(os.Args[2:])
4170
if err != nil {
@@ -67,6 +96,14 @@ func (cli *CLI) Run() {
6796
cli.createBlockchain(*createBlockchainAddress)
6897
}
6998

99+
if createWalletCmd.Parsed() {
100+
cli.createWallet()
101+
}
102+
103+
if listAddressesCmd.Parsed() {
104+
cli.listAddresses()
105+
}
106+
70107
if printChainCmd.Parsed() {
71108
cli.printChain()
72109
}
@@ -80,68 +117,3 @@ func (cli *CLI) Run() {
80117
cli.send(*sendFrom, *sendTo, *sendAmount)
81118
}
82119
}
83-
84-
func (cli *CLI) validateArgs() {
85-
if len(os.Args) < 2 {
86-
cli.printUsage()
87-
os.Exit(1)
88-
}
89-
}
90-
91-
func (cli *CLI) printUsage() {
92-
fmt.Println("Usage:")
93-
fmt.Println(" getbalance -address ADDRESS - Get balance of ADDRESS")
94-
fmt.Println(" createblockchain -address ADDRESS - Create a blockchain and send genesis block reward to ADDRESS")
95-
fmt.Println(" printchain - Print all the blocks of the blockchain")
96-
fmt.Println(" send -from FROM -to TO -amount AMOUNT - Send AMOUNT of coins from FROM address to TO")
97-
}
98-
99-
func (cli *CLI) printChain() {
100-
bc := core.NewBlockchain("")
101-
defer bc.DB.Close()
102-
103-
bci := bc.Iterator()
104-
105-
for {
106-
block := bci.Next()
107-
108-
fmt.Printf("Prev. hash: %x\n", block.PrevBlockHash)
109-
fmt.Printf("Hash: %x\n", block.Hash)
110-
pow := core.NewProofOfWork(block)
111-
fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.Validate()))
112-
fmt.Println()
113-
114-
if len(block.PrevBlockHash) == 0 {
115-
break
116-
}
117-
}
118-
}
119-
120-
func (cli *CLI) getBalance(address string) {
121-
bc := core.NewBlockchain(address)
122-
defer bc.DB.Close()
123-
124-
balance := 0
125-
UTXOs := bc.FindUTXO(address)
126-
127-
for _, out := range UTXOs {
128-
balance += out.Value
129-
}
130-
131-
fmt.Printf("Balance of '%s': %d\n", address, balance)
132-
}
133-
134-
func (cli *CLI) send(from, to string, amount int) {
135-
bc := core.NewBlockchain(from)
136-
defer bc.DB.Close()
137-
138-
tx := core.NewUTXOTransaction(from, to, amount, bc)
139-
bc.MineBlock([]*core.Transaction{tx})
140-
fmt.Println("Success!")
141-
}
142-
143-
func (cli *CLI) createBlockchain(address string) {
144-
bc := core.CreateBlockchain(address)
145-
bc.DB.Close()
146-
fmt.Println("Done!")
147-
}

cli/createblockchain.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package cli
2+
3+
import (
4+
"fmt"
5+
"github.com/sasaxie/go-blockchain/core"
6+
"log"
7+
)
8+
9+
func (cli *CLI) createBlockchain(address string) {
10+
if !core.ValidateAddress(address) {
11+
log.Panic("ERROR: Address is not valid")
12+
}
13+
bc := core.CreateBlockchain(address)
14+
bc.DB.Close()
15+
fmt.Println("Done!")
16+
}

cli/createwallet.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package cli
2+
3+
import (
4+
"fmt"
5+
"github.com/sasaxie/go-blockchain/core"
6+
)
7+
8+
func (cli *CLI) createWallet() {
9+
wallets, _ := core.NewWallets()
10+
address := wallets.CreateWallet()
11+
wallets.SaveToFile()
12+
13+
fmt.Printf("Your new address: %s\n", address)
14+
}

cli/getbalance.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package cli
2+
3+
import (
4+
"fmt"
5+
"github.com/sasaxie/go-blockchain/core"
6+
"github.com/sasaxie/go-blockchain/utils"
7+
"log"
8+
)
9+
10+
func (cli *CLI) getBalance(address string) {
11+
if !core.ValidateAddress(address) {
12+
log.Panic("ERROR: Address is not valid")
13+
}
14+
bc := core.NewBlockchain(address)
15+
defer bc.DB.Close()
16+
17+
balance := 0
18+
pubKeyHash := utils.Base58Decode([]byte(address))
19+
pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4]
20+
UTXOs := bc.FindUTXO(pubKeyHash)
21+
22+
for _, out := range UTXOs {
23+
balance += out.Value
24+
}
25+
26+
fmt.Printf("Balance of '%s': %d\n", address, balance)
27+
}

cli/listaddress.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package cli
2+
3+
import (
4+
"fmt"
5+
"github.com/sasaxie/go-blockchain/core"
6+
"log"
7+
)
8+
9+
func (cli *CLI) listAddresses() {
10+
wallets, err := core.NewWallets()
11+
if err != nil {
12+
log.Panic(err)
13+
}
14+
addresses := wallets.GetAddresses()
15+
16+
for _, address := range addresses {
17+
fmt.Println(address)
18+
}
19+
}

cli/printchain.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package cli
2+
3+
import (
4+
"fmt"
5+
"github.com/sasaxie/go-blockchain/core"
6+
"strconv"
7+
)
8+
9+
func (cli *CLI) printChain() {
10+
bc := core.NewBlockchain("")
11+
defer bc.DB.Close()
12+
13+
bci := bc.Iterator()
14+
15+
for {
16+
block := bci.Next()
17+
18+
fmt.Printf("============ Block %x ============\n", block.Hash)
19+
fmt.Printf("Prev. block: %x\n", block.PrevBlockHash)
20+
pow := core.NewProofOfWork(block)
21+
fmt.Printf("PoW: %s\n\n", strconv.FormatBool(pow.Validate()))
22+
for _, tx := range block.Transactions {
23+
fmt.Println(tx)
24+
}
25+
fmt.Printf("\n\n")
26+
27+
if len(block.PrevBlockHash) == 0 {
28+
break
29+
}
30+
}
31+
}

cli/send.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package cli
2+
3+
import (
4+
"fmt"
5+
"github.com/sasaxie/go-blockchain/core"
6+
"log"
7+
)
8+
9+
func (cli *CLI) send(from, to string, amount int) {
10+
if !core.ValidateAddress(from) {
11+
log.Panic("ERROR: Sender address is not valid")
12+
}
13+
if !core.ValidateAddress(to) {
14+
log.Panic("ERROR: Recipient address is not valid")
15+
}
16+
17+
bc := core.NewBlockchain(from)
18+
defer bc.DB.Close()
19+
20+
tx := core.NewUTXOTransaction(from, to, amount, bc)
21+
bc.MineBlock([]*core.Transaction{tx})
22+
fmt.Println("Success!")
23+
}

0 commit comments

Comments
 (0)