├── .gitignore ├── LICENSE ├── docs ├── ipfs.md └── readme.md ├── examples ├── grpc │ ├── grpc_example │ │ └── grpc_example.go │ ├── hello.pb.go │ ├── hello.pb.gw.go │ ├── hello.proto │ ├── main │ │ ├── client.go │ │ ├── proxy.go │ │ └── server.go │ └── readme.md ├── ipfs │ ├── b58 │ │ └── main.go │ └── cid │ │ └── main.go ├── libp2p │ ├── host │ │ └── main.go │ ├── proxy │ │ └── main.go │ └── readme.md └── rpc_example │ ├── main │ ├── client.go │ └── server.go │ ├── rpc.go │ └── rpc_test.go ├── go.mod ├── go.sum ├── images ├── ipfs.png └── ipfs_init.png ├── readme.md └── src ├── argothrim └── qsort │ ├── qsort.go │ └── qsort_test.go ├── common ├── array.go └── recursion.go ├── database ├── docker-compose.yml ├── leveldb.go ├── mysql.go ├── mysql_test.go ├── readme.md ├── rocksdb.go ├── sql.go └── test.json ├── dpos ├── blockchain.go ├── dpos.go ├── dpos_test.go ├── main │ ├── dpos.go │ └── vote.go ├── p2p.go ├── readme.md └── tools │ └── vote.go ├── graph ├── dag.go ├── dag_test.go ├── graph.go └── graph_test.go ├── hashtable ├── ht.go └── ht_test.go ├── ipfs ├── keystore │ ├── keystore.go │ ├── keystore_test.go │ ├── memkeystore.go │ └── readme.md └── readme.md ├── iterator └── iterator.go ├── libs ├── kademlia │ ├── contract.go │ ├── kademlia.go │ ├── kademlia_test.go │ ├── main │ │ ├── client.go │ │ └── server.go │ ├── node.go │ ├── nodeid.go │ ├── nodeid_test.go │ ├── readme.md │ ├── routingtable.go │ └── routingtable_test.go ├── raft │ └── readme.md └── zk │ ├── docker-compose.yaml │ └── readme.md ├── linklist ├── linked_list.go ├── linked_list_test.go ├── usage.go └── usage_test.go ├── main.go ├── p2p ├── main │ └── main.go ├── p2p.go ├── p2p_test.go └── readme.md ├── pos ├── main │ └── main.go ├── pos.go ├── pos_test.go └── readme.md ├── queue ├── q.go └── q_test.go ├── stack ├── stack.go └── stack_test.go └── tree ├── binary_search_tree.go ├── binary_search_tree_test.go ├── memory_storage.go ├── mpt.go ├── trie.go └── trie_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | .idea 14 | .vscode 15 | vendor 16 | 17 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /docs/ipfs.md: -------------------------------------------------------------------------------- 1 | 2 | [TOC] 3 | 4 | # 简介 5 | 6 | 7 | # 理论介绍 8 | IPFS is the Distributed Web. 9 | 10 | 11 | # IPFS安装 12 | ## Go 安装 13 | go get github.com/ipfs/go-ipfs 14 | 15 | ## 源码安装 16 | 17 | - 下载源码: [源码](https://dist.ipfs.io/#go-ipfs) 18 | - 解压 19 | ``` 20 | tar xvfz go-ipfs.tar.gz 21 | ``` 22 | - 安装 23 | ``` 24 | cd go-ipfs 25 | ./install.sh 26 | ``` 27 | 28 | ## 测试安装 29 | ``` 30 | ipfs --help 31 | ``` 32 | 在终端有如下输出 33 | 34 | 35 | 36 | # IPFS 37 | 38 | ## 0.1 - Quick Start 39 | 40 | This is a set of short examples with minimal explanation. It is meant as 41 | a "quick start". 42 | 43 | 44 | Add a file to ipfs: 45 | 46 | echo "hello world" >hello 47 | ipfs add hello 48 | 49 | 50 | View it: 51 | 52 | ipfs cat 53 | 54 | 55 | Try a directory: 56 | 57 | mkdir foo 58 | mkdir foo/bar 59 | echo "baz" > foo/baz 60 | echo "baz" > foo/bar/baz 61 | ipfs add -r foo 62 | 63 | 64 | View things: 65 | 66 | ipfs ls 67 | ipfs ls /bar 68 | ipfs cat /baz 69 | ipfs cat /bar/baz 70 | ipfs cat /bar 71 | ipfs ls /baz 72 | 73 | 74 | References: 75 | 76 | ipfs refs 77 | ipfs refs -r 78 | ipfs refs --help 79 | 80 | 81 | Get: 82 | 83 | ipfs get -o foo2 84 | diff foo foo2 85 | 86 | 87 | Objects: 88 | 89 | ipfs object get 90 | ipfs object get /foo2 91 | ipfs object --help 92 | 93 | 94 | Pin + GC: 95 | 96 | ipfs pin add 97 | ipfs repo gc 98 | ipfs ls 99 | ipfs pin rm 100 | ipfs repo gc 101 | 102 | 103 | Daemon: 104 | 105 | ipfs daemon (in another terminal) 106 | ipfs id 107 | 108 | 109 | Network: 110 | 111 | (must be online) 112 | ipfs swarm peers 113 | ipfs id 114 | ipfs cat 115 | 116 | 117 | Mount: 118 | 119 | (warning: fuse is finicky!) 120 | ipfs mount 121 | cd /ipfs/ 122 | ls 123 | 124 | 125 | Tool: 126 | 127 | ipfs version 128 | ipfs update 129 | ipfs commands 130 | ipfs config --help 131 | open http://localhost:5001/webui 132 | 133 | 134 | Browse: 135 | 136 | webui: 137 | 138 | http://localhost:5001/webui 139 | 140 | video: 141 | 142 | http://localhost:8080/ipfs/QmVc6zuAneKJzicnJpfrqCH9gSy6bz54JhcypfJYhGUFQu/play#/ipfs/QmTKZgRNwDNZwHtJSjCp6r5FYefzpULfy37JvMt9DwvXse 143 | 144 | images: 145 | 146 | http://localhost:8080/ipfs/QmZpc3HvfjEXvLWGQPWbHk3AjD5j8NEN4gmFN8Jmrd5g83/cs 147 | 148 | markdown renderer app: 149 | 150 | http://localhost:8080/ipfs/QmX7M9CiYXjVeFnkfVGf3y5ixTZ2ACeSGyL1vBJY1HvQPp/mdown 151 | 152 | 153 | 154 | # 参考 155 | 156 | - https://www.youtube.com/watch?v=8CMxDNuuAiQ -------------------------------------------------------------------------------- /docs/readme.md: -------------------------------------------------------------------------------- 1 | # ipfs 2 | 如果说2018年我最期待的项目,IPFS星际文件系统无疑是第一位的. IPFS(filecoin)在2017年8月份创纪录地募集到了2.5亿美金, 而这次Token sale仅仅只出售了10%的代币,这意味着 3 | IPFS还没正式上线,市值就达到了25亿美金. 4 | 5 | # 6 | ipfs 是一个分布式文件系统交换协议.IPFS协议定义了文件在分布式系统中如何存储,索引和传输. IPFS的目标是通过一个文件系统讲网络中的所有设备链接起来.在某方面IPFS和WEB原本的设计很像, 7 | 但是IPFS更像是由很多个节点组成的P2P的git文件系统.如果IPFS使用得当,IPFS将可以代替HTTP协议. 8 | 9 | IPFS是一种点对点的超媒体文件存储,索引.交换协议 10 | 11 | Filecoin的经济模型 12 | - Host为网络提供多余的存储 13 | - Retriver为网络中的节点提供带宽,帮其他用户传输文件. 所以在ipfs中有两种挖矿的方式/ 14 | 15 | 16 | IPFS由一位来自墨西哥的小伙子Huan Benet于2014年5月发明. Juan Benet毕业于斯坦福,在2015年参与了大名鼎鼎的Ycombinator计划,并成功创立了Protocol Lab实验室. 到目前为止, 17 | Protocol Lab实验室已经又有上百位代码贡献者和14位核心开发人员. IPFS的开发进度非常好,到目前为止已经发布了27个版本. -------------------------------------------------------------------------------- /examples/grpc/grpc_example/grpc_example.go: -------------------------------------------------------------------------------- 1 | package grpc_example 2 | 3 | import ( 4 | "log" 5 | "net" 6 | "os" 7 | "golang.org/x/net/context" 8 | pb "github.com/csunny/argo/examples/grpc" 9 | "google.golang.org/grpc" 10 | "google.golang.org/grpc/reflection" 11 | "flag" 12 | "github.com/grpc-ecosystem/grpc-gateway/runtime" 13 | "net/http" 14 | ) 15 | 16 | const ( 17 | port = ":9090" 18 | defaultName = "Magic" 19 | ) 20 | 21 | // server 22 | type server struct{} 23 | 24 | // SayHello implements helloworld.GreeterServer 25 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 26 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 27 | } 28 | 29 | func RunServer() { 30 | log.Println("server is running at 127.0.0.1:9090... ") 31 | 32 | lis, err := net.Listen("tcp", port) 33 | if err != nil { 34 | log.Fatalf("failed to listen: %v", err) 35 | } 36 | s := grpc.NewServer() 37 | pb.RegisterGreeterServer(s, &server{}) 38 | // Register reflection service on gRPC server. 39 | reflection.Register(s) 40 | if err := s.Serve(lis); err != nil { 41 | log.Fatalf("failed to serve: %v", err) 42 | } 43 | } 44 | 45 | 46 | func Client() { 47 | // set up a connection to the server 48 | conn, err := grpc.Dial("localhost:9090", grpc.WithInsecure()) 49 | if err != nil { 50 | log.Fatal(err) 51 | } 52 | 53 | defer conn.Close() 54 | c := pb.NewGreeterClient(conn) 55 | 56 | // Contract the server and print response 57 | name := defaultName 58 | if len(os.Args) > 1 { 59 | name = os.Args[1] 60 | } 61 | 62 | r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name:name}) 63 | if err != nil{ 64 | log.Fatal("could not greet:", err) 65 | } 66 | log.Println("Greeting: ", r.Message) 67 | } 68 | 69 | 70 | var ( 71 | helloEndPoint = flag.String("hello_endpoint", "localhost:9090", "endpoint of your service") 72 | ) 73 | func Proxy() error { 74 | ctx := context.Background() 75 | ctx, cancel := context.WithCancel(ctx) 76 | 77 | defer cancel() 78 | 79 | mux := runtime.NewServeMux() 80 | opts := []grpc.DialOption{grpc.WithInsecure()} 81 | 82 | err := pb.RegisterGreeterHandlerFromEndpoint(ctx, mux, *helloEndPoint, opts) 83 | if err != nil{ 84 | return err 85 | } 86 | 87 | log.Println("The Server is running at 127.0.0.1:8888") 88 | return http.ListenAndServe(":8888", mux) 89 | } 90 | 91 | -------------------------------------------------------------------------------- /examples/grpc/hello.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: hello.proto 3 | 4 | /* 5 | Package hello is a generated protocol buffer package. 6 | 7 | It is generated from these files: 8 | hello.proto 9 | 10 | It has these top-level messages: 11 | HelloRequest 12 | HelloReply 13 | */ 14 | package hello 15 | 16 | import proto "github.com/golang/protobuf/proto" 17 | import fmt "fmt" 18 | import math "math" 19 | 20 | import ( 21 | context "golang.org/x/net/context" 22 | grpc "google.golang.org/grpc" 23 | ) 24 | 25 | // Reference imports to suppress errors if they are not otherwise used. 26 | var _ = proto.Marshal 27 | var _ = fmt.Errorf 28 | var _ = math.Inf 29 | 30 | // This is a compile-time assertion to ensure that this generated file 31 | // is compatible with the proto package it is being compiled against. 32 | // A compilation error at this line likely means your copy of the 33 | // proto package needs to be updated. 34 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 35 | 36 | // The request message containing the user's name. 37 | type HelloRequest struct { 38 | Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` 39 | } 40 | 41 | func (m *HelloRequest) Reset() { *m = HelloRequest{} } 42 | func (m *HelloRequest) String() string { return proto.CompactTextString(m) } 43 | func (*HelloRequest) ProtoMessage() {} 44 | func (*HelloRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 45 | 46 | func (m *HelloRequest) GetName() string { 47 | if m != nil { 48 | return m.Name 49 | } 50 | return "" 51 | } 52 | 53 | // The response message containing the greetings 54 | type HelloReply struct { 55 | Message string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"` 56 | } 57 | 58 | func (m *HelloReply) Reset() { *m = HelloReply{} } 59 | func (m *HelloReply) String() string { return proto.CompactTextString(m) } 60 | func (*HelloReply) ProtoMessage() {} 61 | func (*HelloReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 62 | 63 | func (m *HelloReply) GetMessage() string { 64 | if m != nil { 65 | return m.Message 66 | } 67 | return "" 68 | } 69 | 70 | func init() { 71 | proto.RegisterType((*HelloRequest)(nil), "hello.HelloRequest") 72 | proto.RegisterType((*HelloReply)(nil), "hello.HelloReply") 73 | } 74 | 75 | // Reference imports to suppress errors if they are not otherwise used. 76 | var _ context.Context 77 | var _ grpc.ClientConn 78 | 79 | // This is a compile-time assertion to ensure that this generated file 80 | // is compatible with the grpc package it is being compiled against. 81 | const _ = grpc.SupportPackageIsVersion4 82 | 83 | // Client API for Greeter service 84 | 85 | type GreeterClient interface { 86 | // Sends a greeting 87 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 88 | } 89 | 90 | type greeterClient struct { 91 | cc *grpc.ClientConn 92 | } 93 | 94 | func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { 95 | return &greeterClient{cc} 96 | } 97 | 98 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 99 | out := new(HelloReply) 100 | err := grpc.Invoke(ctx, "/hello.Greeter/SayHello", in, out, c.cc, opts...) 101 | if err != nil { 102 | return nil, err 103 | } 104 | return out, nil 105 | } 106 | 107 | // Server API for Greeter service 108 | 109 | type GreeterServer interface { 110 | // Sends a greeting 111 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 112 | } 113 | 114 | func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { 115 | s.RegisterService(&_Greeter_serviceDesc, srv) 116 | } 117 | 118 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 119 | in := new(HelloRequest) 120 | if err := dec(in); err != nil { 121 | return nil, err 122 | } 123 | if interceptor == nil { 124 | return srv.(GreeterServer).SayHello(ctx, in) 125 | } 126 | info := &grpc.UnaryServerInfo{ 127 | Server: srv, 128 | FullMethod: "/hello.Greeter/SayHello", 129 | } 130 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 131 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 132 | } 133 | return interceptor(ctx, in, info, handler) 134 | } 135 | 136 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 137 | ServiceName: "hello.Greeter", 138 | HandlerType: (*GreeterServer)(nil), 139 | Methods: []grpc.MethodDesc{ 140 | { 141 | MethodName: "SayHello", 142 | Handler: _Greeter_SayHello_Handler, 143 | }, 144 | }, 145 | Streams: []grpc.StreamDesc{}, 146 | Metadata: "hello.proto", 147 | } 148 | 149 | func init() { proto.RegisterFile("hello.proto", fileDescriptor0) } 150 | 151 | var fileDescriptor0 = []byte{ 152 | // 136 bytes of a gzipped FileDescriptorProto 153 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0xce, 0x48, 0xcd, 0xc9, 154 | 0xc9, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x05, 0x73, 0x94, 0x94, 0xb8, 0x78, 0x3c, 155 | 0x40, 0x8c, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, 0x21, 0x21, 0x2e, 0x96, 0xbc, 0xc4, 0xdc, 156 | 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x30, 0x5b, 0x49, 0x8d, 0x8b, 0x0b, 0xaa, 0xa6, 157 | 0x20, 0xa7, 0x52, 0x48, 0x82, 0x8b, 0x3d, 0x37, 0xb5, 0xb8, 0x38, 0x31, 0x1d, 0xa6, 0x08, 0xc6, 158 | 0x35, 0xb2, 0xe7, 0x62, 0x77, 0x2f, 0x4a, 0x4d, 0x2d, 0x49, 0x2d, 0x12, 0x32, 0xe1, 0xe2, 0x08, 159 | 0x4e, 0xac, 0x04, 0xeb, 0x12, 0x12, 0xd6, 0x83, 0xd8, 0x8b, 0x6c, 0x8f, 0x94, 0x20, 0xaa, 0x60, 160 | 0x41, 0x4e, 0xa5, 0x12, 0x43, 0x12, 0x1b, 0xd8, 0x69, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 161 | 0xf4, 0xbe, 0xdb, 0x94, 0xa9, 0x00, 0x00, 0x00, 162 | } 163 | -------------------------------------------------------------------------------- /examples/grpc/hello.pb.gw.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. 2 | // source: hello.proto 3 | 4 | /* 5 | Package hello is a reverse proxy. 6 | 7 | It translates gRPC into RESTful JSON APIs. 8 | */ 9 | package hello 10 | 11 | import ( 12 | "io" 13 | "net/http" 14 | 15 | "github.com/golang/protobuf/proto" 16 | "github.com/grpc-ecosystem/grpc-gateway/runtime" 17 | "github.com/grpc-ecosystem/grpc-gateway/utilities" 18 | "golang.org/x/net/context" 19 | "google.golang.org/grpc" 20 | "google.golang.org/grpc/codes" 21 | "google.golang.org/grpc/grpclog" 22 | "google.golang.org/grpc/status" 23 | ) 24 | 25 | var _ codes.Code 26 | var _ io.Reader 27 | var _ status.Status 28 | var _ = runtime.String 29 | var _ = utilities.NewDoubleArray 30 | 31 | func request_Greeter_SayHello_0(ctx context.Context, marshaler runtime.Marshaler, client GreeterClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { 32 | var protoReq HelloRequest 33 | var metadata runtime.ServerMetadata 34 | 35 | if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { 36 | return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) 37 | } 38 | 39 | msg, err := client.SayHello(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) 40 | return msg, metadata, err 41 | 42 | } 43 | 44 | // RegisterGreeterHandlerFromEndpoint is same as RegisterGreeterHandler but 45 | // automatically dials to "endpoint" and closes the connection when "ctx" gets done. 46 | func RegisterGreeterHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { 47 | conn, err := grpc.Dial(endpoint, opts...) 48 | if err != nil { 49 | return err 50 | } 51 | defer func() { 52 | if err != nil { 53 | if cerr := conn.Close(); cerr != nil { 54 | grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) 55 | } 56 | return 57 | } 58 | go func() { 59 | <-ctx.Done() 60 | if cerr := conn.Close(); cerr != nil { 61 | grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) 62 | } 63 | }() 64 | }() 65 | 66 | return RegisterGreeterHandler(ctx, mux, conn) 67 | } 68 | 69 | // RegisterGreeterHandler registers the http handlers for service Greeter to "mux". 70 | // The handlers forward requests to the grpc endpoint over "conn". 71 | func RegisterGreeterHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { 72 | return RegisterGreeterHandlerClient(ctx, mux, NewGreeterClient(conn)) 73 | } 74 | 75 | // RegisterGreeterHandlerClient registers the http handlers for service Greeter 76 | // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "GreeterClient". 77 | // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "GreeterClient" 78 | // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in 79 | // "GreeterClient" to call the correct interceptors. 80 | func RegisterGreeterHandlerClient(ctx context.Context, mux *runtime.ServeMux, client GreeterClient) error { 81 | 82 | mux.Handle("POST", pattern_Greeter_SayHello_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { 83 | ctx, cancel := context.WithCancel(req.Context()) 84 | defer cancel() 85 | if cn, ok := w.(http.CloseNotifier); ok { 86 | go func(done <-chan struct{}, closed <-chan bool) { 87 | select { 88 | case <-done: 89 | case <-closed: 90 | cancel() 91 | } 92 | }(ctx.Done(), cn.CloseNotify()) 93 | } 94 | inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) 95 | rctx, err := runtime.AnnotateContext(ctx, mux, req) 96 | if err != nil { 97 | runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) 98 | return 99 | } 100 | resp, md, err := request_Greeter_SayHello_0(rctx, inboundMarshaler, client, req, pathParams) 101 | ctx = runtime.NewServerMetadataContext(ctx, md) 102 | if err != nil { 103 | runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) 104 | return 105 | } 106 | 107 | forward_Greeter_SayHello_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) 108 | 109 | }) 110 | 111 | return nil 112 | } 113 | 114 | var ( 115 | pattern_Greeter_SayHello_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "hello"}, "")) 116 | ) 117 | 118 | var ( 119 | forward_Greeter_SayHello_0 = runtime.ForwardResponseMessage 120 | ) 121 | -------------------------------------------------------------------------------- /examples/grpc/hello.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package hello; 4 | 5 | import "google/api/annotations.proto"; 6 | 7 | service Greeter { 8 | // Sends a greeting 9 | rpc SayHello (HelloRequest) returns (HelloReply) { 10 | option(google.api.http) = { 11 | post: "/v1/example/hello" 12 | body: "*" 13 | }; 14 | 15 | } 16 | } 17 | 18 | // The request message containing the user's name. 19 | message HelloRequest { 20 | string name = 1; 21 | } 22 | 23 | // The response message containing the greetings 24 | message HelloReply { 25 | string message = 1; 26 | } -------------------------------------------------------------------------------- /examples/grpc/main/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | mgrpc "github.com/csunny/argo/examples/grpc/grpc_example" 5 | ) 6 | 7 | func main() { 8 | mgrpc.Client() 9 | } -------------------------------------------------------------------------------- /examples/grpc/main/proxy.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | 5 | "flag" 6 | "github.com/golang/glog" 7 | mgrpc "github.com/csunny/argo/examples/grpc/grpc_example" 8 | ) 9 | func main() { 10 | flag.Parse() 11 | 12 | defer glog.Flush() 13 | 14 | if err := mgrpc.Proxy(); err != nil{ 15 | glog.Fatal(err) 16 | } 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /examples/grpc/main/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | mgrpc "github.com/csunny/argo/examples/grpc/grpc_example" 5 | ) 6 | 7 | func main() { 8 | mgrpc.RunServer() 9 | } -------------------------------------------------------------------------------- /examples/grpc/readme.md: -------------------------------------------------------------------------------- 1 | # 生成gRPC代码 2 | 3 | ``` 4 | protoc -I grpc grpc/hello.proto --go_out=plugins=grpc:grpc 5 | ``` 6 | 7 | 8 | ``` 9 | 1. generate grpc stub 10 | 11 | protoc -I/usr/local/include -I. \ 12 | -I$GOPATH/src \ 13 | -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ 14 | --go_out=plugins=grpc:. \ 15 | --grpc-gateway_out=logtostderr=true:. \ 16 | ./hello.proto 17 | 18 | 19 | 2. Generate reverse-proxy 20 | 21 | protoc -I/usr/local/include -I. \ 22 | -I$GOPATH/src \ 23 | -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ 24 | --grpc-gateway_out=logtostderr=true:. \ 25 | ./hello.proto 26 | 27 | 28 | protoc -I/usr/local/include -I. \ 29 | -I$GOPATH/src \ 30 | -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ 31 | --grpc-gateway_out=logtostderr=true:. \ 32 | ./hello.proto 33 | 34 | ``` -------------------------------------------------------------------------------- /examples/ipfs/b58/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/multiformats/go-multihash" 6 | ) 7 | 8 | // ID magic test id convert 9 | type ID string 10 | 11 | 12 | func main(){ 13 | m, err := multihash.FromB58String("QmNsDs3LCDsvGaPazxdNw3izm2bQ1enwMYhEtRpRrPvHyX") 14 | if err != nil{ 15 | fmt.Println(err) 16 | } 17 | 18 | res := ID(m) 19 | fmt.Println(res) 20 | } -------------------------------------------------------------------------------- /examples/ipfs/cid/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * cid is the ipfs content identify module 3 | * in this module we known how a content convert a hashed id 4 | */ 5 | 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | "io/ioutil" 11 | 12 | "github.com/ipfs/go-cid" 13 | ) 14 | 15 | const ( 16 | // File is the test file 17 | File = "./argo/docs/readme.md" 18 | ) 19 | 20 | func main() { 21 | 22 | p := cid.Prefix{ 23 | Version: 0, 24 | Codec: 0x70, // prtobuf 25 | MhType: 0x12, // sha2-256 26 | MhLength: -1, 27 | } 28 | 29 | data, err := ioutil.ReadFile(File) 30 | if err != nil { 31 | panic(err) 32 | } 33 | 34 | fcid, err := p.Sum(data) 35 | if err != nil{ 36 | panic(err) 37 | } 38 | 39 | fmt.Println(fcid) 40 | 41 | } 42 | -------------------------------------------------------------------------------- /examples/libp2p/host/main.go: -------------------------------------------------------------------------------- 1 | /* For the most applications , the host is the basic 2 | building block you'll need to get started. The guide will show how to 3 | constrant and use a simple host.package main 4 | 5 | The host is an abstraction that managers services on top of a swarm, 6 | it provides a clean interface to connect to a service on a given remote peer. 7 | 8 | if you want to create a host with a default configuration, you can do the following: 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "context" 15 | "crypto/rand" 16 | "fmt" 17 | 18 | libp2p "github.com/libp2p/go-libp2p" 19 | crypto "github.com/libp2p/go-libp2p-crypto" 20 | ) 21 | 22 | func main(){ 23 | // The context governs the lifetime of the libp2p node 24 | 25 | ctx, cancel := context.WithCancel(context.Background()) 26 | defer cancel() 27 | 28 | // to construct a simple host with all the default settings, just use New 29 | h, err := libp2p.New(ctx) 30 | if err != nil{ 31 | panic(err) 32 | } 33 | 34 | fmt.Printf("Hello world, my hosts ID is %s\n", h.ID()) 35 | 36 | // set your own keypair 37 | priv, _, err := crypto.GenerateEd25519Key(rand.Reader) 38 | if err != nil{ 39 | panic(err) 40 | } 41 | 42 | h2, err := libp2p.New(ctx, libp2p.Identity(priv), 43 | // set your owner listen address 44 | // the config takes an array of addresses, specify as many as 45 | // you want. 46 | libp2p.ListenAddrStrings("/ip4/0.0.0.0/tcp/9000"), 47 | ) 48 | if err != nil{ 49 | panic(err) 50 | } 51 | 52 | fmt.Printf("Hello world, my second hosts ID is %s\n", h2.ID()) 53 | } -------------------------------------------------------------------------------- /examples/libp2p/proxy/main.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/csunny/argo/2eef10dda485b38369431ebb5e2735c528ad1a78/examples/libp2p/proxy/main.go -------------------------------------------------------------------------------- /examples/libp2p/readme.md: -------------------------------------------------------------------------------- 1 | ## This is the example of libp2p 2 | -------------------------------------------------------------------------------- /examples/rpc_example/main/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/csunny/argo/examples/rpc_example" 5 | ) 6 | 7 | func main() { 8 | rpc_example.Client() 9 | } 10 | -------------------------------------------------------------------------------- /examples/rpc_example/main/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/csunny/argo/examples/rpc_example" 5 | ) 6 | func main() { 7 | rpc_example.Server() 8 | } 9 | 10 | 11 | -------------------------------------------------------------------------------- /examples/rpc_example/rpc.go: -------------------------------------------------------------------------------- 1 | package rpc_example 2 | 3 | import ( 4 | "net/rpc" 5 | "net" 6 | "log" 7 | "fmt" 8 | ) 9 | 10 | type Greeter struct { 11 | 12 | } 13 | 14 | func (p *Greeter) Greet(request string, response *string) error { 15 | *response = "Hello: " + request 16 | return nil 17 | } 18 | 19 | func Server() { 20 | rpc.RegisterName("Greeter", new(Greeter)) 21 | listener, err := net.Listen("tcp", ":8888") 22 | 23 | fmt.Println("Server is running at localhost:8888...") 24 | if err != nil{ 25 | log.Fatal("ListenTCP error:", err) 26 | } 27 | 28 | conn, err := listener.Accept() 29 | if err != nil{ 30 | log.Fatal("Accept error", err) 31 | } 32 | 33 | rpc.ServeConn(conn) 34 | } 35 | 36 | func Client() { 37 | client, err := rpc.Dial("tcp", "localhost:8888") 38 | if err != nil{ 39 | log.Fatal("dialing:", err) 40 | } 41 | 42 | var response string 43 | err = client.Call("Greeter.Greet", "magic", &response) 44 | if err != nil{ 45 | log.Fatal(err) 46 | } 47 | 48 | fmt.Println(response) 49 | } -------------------------------------------------------------------------------- /examples/rpc_example/rpc_test.go: -------------------------------------------------------------------------------- 1 | package rpc_example 2 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/csunny/argo 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/davecgh/go-spew v1.1.1 7 | github.com/go-sql-driver/mysql v1.4.0 8 | github.com/golang/glog v1.0.0 9 | github.com/golang/protobuf v1.5.2 10 | github.com/grpc-ecosystem/grpc-gateway v1.16.0 11 | github.com/ipfs/go-cid v0.1.0 12 | github.com/ipfs/go-log v1.0.5 13 | github.com/libp2p/go-libp2p v0.17.0 14 | github.com/libp2p/go-libp2p-crypto v0.1.0 15 | github.com/libp2p/go-libp2p-host v0.1.0 16 | github.com/libp2p/go-libp2p-net v0.1.0 17 | github.com/libp2p/go-libp2p-peer v0.2.0 18 | github.com/libp2p/go-libp2p-peerstore v0.6.0 19 | github.com/multiformats/go-multiaddr v0.4.1 20 | github.com/multiformats/go-multihash v0.0.15 21 | github.com/whyrusleeping/go-logging v0.0.0-20170515211332-0457bb6b88fc 22 | golang.org/x/net v0.0.0-20211216030914-fe4d6282115f 23 | google.golang.org/appengine v1.6.7 // indirect 24 | google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa // indirect 25 | google.golang.org/grpc v1.43.0 26 | ) 27 | -------------------------------------------------------------------------------- /images/ipfs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/csunny/argo/2eef10dda485b38369431ebb5e2735c528ad1a78/images/ipfs.png -------------------------------------------------------------------------------- /images/ipfs_init.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/csunny/argo/2eef10dda485b38369431ebb5e2735c528ad1a78/images/ipfs_init.png -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ### 项目简介 2 | 3 | 介绍数据结构与算法,涵盖字符串、数组、链表、队列、栈、树、图等一系列的数据结构,同时也会注重算法的应用。在理论知识的基础上,注重算法的go语言实现。 4 | 5 | 本教程注重数据结构与算法基础,目的不为刷题,但为了照顾部分同学,会加入经典的数据结构与算法面试题目,很多题目都是大厂喜欢问的面试题目。 6 | 7 | ### 适宜人群 8 | - 非计算机专业,但是对计算机感兴趣的同学 9 | - 数据结构与算法基础不扎实的同学 10 | - 希望拿到满意offer,有面试需求的同学 11 | - 了解算法理论,但是不知道如何用go语言实现的同学 12 | 13 | ### 你会得到的收获 14 | - 熟悉数据结构与算法 15 | - 掌握go编程语言 16 | - 一份满意的offer 17 | 18 | 19 | ### 大话Go语言 20 | 21 | 2009年,Go语言诞生了!正如历史上其他一切新事物一样,Go也有它自己的梦想与使命。2009年,我自认为不管是在计算机软件发展史、还是在人类发展史上,都是一个相当重要的年份。2008年金融危机爆发,经济下行全球产生信任危机。从此绝大多数行业开始走向转折,互联网行业跟随时代的步伐,异军突起,开始了草莽式的发展。 22 | 23 | 正是在这样的历史时刻,Go语言作为Google的金宝贝(Golden son)在一批大牛的怀抱中诞生了,诞生之初就自诩为互联网时代的C语言。然而,也正是这一年,在另一边的芬兰赫尔辛基,中本村用C++语言实现了比特币的代码,挖出了世界上第一枚比特币。 历史总是惊人的巧合,或许在当时没人能够想到,这两个完全不同的事情,对人类发展史有如此重大的影响。 现如今,Go跟C++作为区块链底层技术领域的双雄,正在改变历史。 或许今天,这种改变你可能还没意识到,或者没体会到,但我要告诉你,Time is changed! 24 | 25 | 当然,Go语言诞生的本意并不是成为区块链底层技术开发的主流语言,就像我前面提到的,它有自己的梦想与使命。08年前后,随着互联网的高速发展,对网站的性能提出了越来越多的挑战,所以并发与分布式成为了工程师们关注的焦点。 此外不同与传统的大型服务器,互联网行业一方面为了适应高速发展的需求,同时降低资源成本,多核化与集群化是互联网时代的典型特点。Go语言作为互联网时代诞生的语言,一开始就顺应时代,天然支持高并发。 26 | 27 | 28 | 经过这么多年的发展之后,技术工程师们希望在保持高性能的基础上,在开发使用方面也能够保持足够的轻量、简单,同时又能适应大规模的软件工程开发工作。所以工程师们带着这些要求,重新出发,在借鉴前人的基础上,又推翻了之前存在的很多东西,另辟蹊径,终于在2009年,Go语言出现在了我们面前。 29 | 30 | 不同于其他绝大多数语言,由于Go语言本身就出身在大户人家,所以天生就发育良好。到2013年,Docker的出现吹响了go语言开疆扩土的号角。此后随着k8s、 docker-swarm 等一批基于pass平台的技术出现之后,Go语言正式成为了云计算领域的绝对主角。好巧不巧,同样也是在2013年,ethereum基金会成立,融资开发ethereum平台,2015年随着ethereum的发布上线,ethereum成为了比特币之后第二影响力的公链。而让人兴奋的是,ethereum是基于Go语言开发的,从此go语言跟C++一样成为了区块链底层开发技术的不二之选。 31 | 32 | 今年是2018年,Go语言已经应用在了很多产品当中,同时也有很多杀手级的应用。 33 | 34 | 谁也无法阻止历史的车轮,未来的事情会是怎么样,我们谁都无法预测。但,在当下,Go语言作为高并发与分布式系统领域最炙手可热的语言,值得我们去学习,去钻研,去探讨! 35 | 36 | ### 代码目录 37 | - examples 38 | - [RPC实战](https://github.com/csunny/argo/tree/master/examples/rpc_example) 39 | - [GRPC实战](https://github.com/csunny/argo/tree/master/examples/grpc) 40 | 41 | - src 42 | - 数据结构与算法 43 | - [快速排序](https://github.com/csunny/argo/tree/master/src/argothrim/qsort) 44 | - [切片操作与反转](https://github.com/csunny/argo/blob/master/src/common/array.go) 45 | - [递归实现](https://github.com/csunny/argo/blob/master/src/common/recursion.go) 46 | - [二叉搜索树](https://github.com/csunny/argo/tree/master/src/tree) 47 | - [链表](https://github.com/csunny/argo/tree/master/src/linklist) 48 | - [图](https://github.com/csunny/argo/tree/master/src/graph) 49 | - [队列](https://github.com/csunny/argo/tree/master/src/queue) 50 | - [栈](https://github.com/csunny/argo/tree/master/src/stack) 51 | - [迭代器实现](https://github.com/csunny/argo/tree/master/src/iterator) 52 | - [哈希表](https://github.com/csunny/argo/tree/master/src/hashtable) 53 | - 分布式算法实现 54 | - [POS算法实现](https://github.com/csunny/argo/tree/master/src/pos) 55 | - [DPOS算法实现](https://github.com/csunny/argo/tree/master/src/dpos) 56 | - [DHT(分布式hash表实现)](https://github.com/csunny/argo/tree/master/src/libs/kademlia) 57 | - 分布式网络(P2P) 58 | - [P2P对等网络]() 59 | - [一个基于P2P对等网络的区块链实现](https://github.com/csunny/argo/tree/master/src/p2p) 60 | ### 文档地址 61 | - https://xiaozhuanlan.com/argo 62 | 63 | 64 | ### Licence 65 | argo code is licensed under the Apache 66 | -------------------------------------------------------------------------------- /src/argothrim/qsort/qsort.go: -------------------------------------------------------------------------------- 1 | package qsort 2 | 3 | func QuickSort(values []int) []int { 4 | if len(values) <= 1{ 5 | return values 6 | } 7 | 8 | mid := values[0] // 基准值 9 | head, tail := 0, len(values) - 1 10 | 11 | // 遍历整个切片 12 | for i :=1; i <= tail; { 13 | if values[i] > mid{ 14 | // 小的数据放在基准值左侧 15 | values[i], values[tail] = values[tail], values[i] 16 | tail -- 17 | }else { 18 | values[i], values[head] = values[head], values[i] 19 | head ++ 20 | i ++ 21 | } 22 | } 23 | QuickSort(values[:head]) 24 | QuickSort(values[head+1:]) 25 | 26 | return values 27 | } 28 | -------------------------------------------------------------------------------- /src/argothrim/qsort/qsort_test.go: -------------------------------------------------------------------------------- 1 | package qsort 2 | 3 | import "testing" 4 | 5 | func TestQuickSort(t *testing.T) { 6 | values := []int{5, 4, 3, 2, 1} 7 | QuickSort(values) 8 | 9 | if values[0] != 1 || values[1] != 2|| values[2] != 3 || values[3] != 4 || values[4] !=5{ 10 | t.Error("QuictSort() failed . Got", values, "Excepted 1, 2, 3, 4, 5") 11 | } 12 | } 13 | 14 | func TestQuickSort2(t *testing.T) { 15 | values := []int {5, 5, 3, 2, 1} 16 | QuickSort(values) 17 | 18 | if values[0] != 1 || values[1] != 2 || values[2] != 3 || values[3] != 5 || values[4] != 5{ 19 | t.Error("BubbleSort() failed. Got ", values, "Expected 1 2 3 5 5") 20 | } 21 | } 22 | 23 | func TestQuickSort3(t *testing.T) { 24 | values := []int{5} 25 | QuickSort(values) 26 | if values[0] != 5{ 27 | t.Error("BubbleSort() failed. Got ", values, "Excepted 5") 28 | } 29 | } -------------------------------------------------------------------------------- /src/common/array.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func Arr() { 8 | a := [2] int{1, 2} // 数组, 一开始就分配好了内存,大小限定,不能拓展 9 | b := []int{1, 2, 3, 4, 5, 6, 7} // 切片,大小没有限定,可以动态拓展 10 | 11 | for _, i := range a{ 12 | fmt.Printf("a 数组遍历 %d\n", i) 13 | } 14 | 15 | for _, j := range b{ 16 | fmt.Printf("b 切片遍历 %d\n", j) 17 | } 18 | 19 | //输出数组的第二个元素 20 | fmt.Printf("a的第二个元素 %d\n", a[1]) 21 | 22 | // 输出切片的第五个元素 23 | fmt.Printf("b的第五个元素 %d\n", b[4]) 24 | } 25 | 26 | func Insert(p int, value int, s []int) []int { 27 | // 给切片插入元素 p为插入位置 value 是插入值 s是原来的数组 28 | 29 | result := append(s[:p], value) 30 | result = append(result, s[p:]...) 31 | return result 32 | } 33 | 34 | func Reverse(s []int) { 35 | // 反转一个切片 36 | // 此处利用go语言多重赋值的特性 37 | for i, j:=0, len(s)-1; i 1 { 28 | vote, err := strconv.Atoi(nodeSplit[1]) 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | voteList = append(voteList, vote) 33 | voteMap[nodeSplit[0]] = vote 34 | } 35 | } 36 | sort.Slice(voteList, func(i, j int) bool { 37 | return voteList[i] > voteList[j] 38 | }) 39 | 40 | if len(voteList) > BPCount { 41 | voteList = voteList[0:BPCount] // 选择前面的5个节点作为Block producer 42 | } 43 | 44 | for k, v := range voteMap { 45 | if v > voteList[len(voteList)-1] { 46 | bp = k 47 | } 48 | } 49 | return 50 | } 51 | -------------------------------------------------------------------------------- /src/dpos/dpos_test.go: -------------------------------------------------------------------------------- 1 | package dpos 2 | 3 | import "testing" 4 | 5 | func TestPickWinner(t *testing.T) { 6 | PickWinner() 7 | } -------------------------------------------------------------------------------- /src/dpos/main/dpos.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/csunny/argo/src/dpos" 4 | 5 | func main() { 6 | dpos.Run() 7 | } -------------------------------------------------------------------------------- /src/dpos/main/vote.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/csunny/argo/src/dpos/tools" 5 | ) 6 | func main() { 7 | tools.Vote() 8 | } -------------------------------------------------------------------------------- /src/dpos/p2p.go: -------------------------------------------------------------------------------- 1 | // This is the p2p network, handler the conn and communicate with nodes each other. 2 | // this file is created by magic at 2018-9-2 3 | 4 | package dpos 5 | 6 | import ( 7 | "io" 8 | "fmt" 9 | "os" 10 | "strings" 11 | "strconv" 12 | "time" 13 | "crypto/rand" 14 | "flag" 15 | "log" 16 | "bufio" 17 | "sync" 18 | "encoding/json" 19 | "context" 20 | mrand "math/rand" 21 | "github.com/libp2p/go-libp2p-net" 22 | "github.com/libp2p/go-libp2p-host" 23 | "github.com/libp2p/go-libp2p-crypto" 24 | "github.com/libp2p/go-libp2p" 25 | "github.com/libp2p/go-libp2p-peer" 26 | ma "github.com/multiformats/go-multiaddr" 27 | pstore "github.com/libp2p/go-libp2p-peerstore" 28 | "github.com/davecgh/go-spew/spew" 29 | ) 30 | 31 | const DefaultVote = 10 32 | const FileName = "config.ini" 33 | 34 | var mutex = &sync.Mutex{} 35 | 36 | type Validator struct { 37 | name string 38 | vote int 39 | } 40 | 41 | func MakeBasicHost(listenPort int, secio bool, randseed int64) (host.Host, error) { 42 | var r io.Reader 43 | 44 | if randseed == 0 { 45 | r = rand.Reader 46 | } else { 47 | r = mrand.New(mrand.NewSource(randseed)) 48 | } 49 | 50 | // 生产一对公私钥 51 | priv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r) 52 | if err != nil { 53 | return nil, err 54 | } 55 | 56 | opts := []libp2p.Option{ 57 | libp2p.ListenAddrStrings(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", listenPort)), 58 | libp2p.Identity(priv), 59 | } 60 | 61 | if !secio { 62 | opts = append(opts, libp2p.NoSecurity) 63 | } 64 | basicHost, err := libp2p.New(context.Background(), opts...) 65 | if err != nil { 66 | return nil, err 67 | } 68 | 69 | // Build host multiaddress 70 | hostAddr, _ := ma.NewMultiaddr(fmt.Sprintf("/ipfs/%s", basicHost.ID().Pretty())) 71 | 72 | // Now we can build a full multiaddress to reach this host 73 | // by encapsulating both addresses; 74 | addr := basicHost.Addrs()[0] 75 | fullAddr := addr.Encapsulate(hostAddr) 76 | 77 | log.Printf("我是: %s\n", fullAddr) 78 | SavePeer(basicHost.ID().Pretty()) 79 | 80 | if secio { 81 | log.Printf("现在在一个新终端运行命令: 'go run main/dpos.go -l %d -d %s -secio'\n ", listenPort+1, fullAddr) 82 | } else { 83 | log.Printf("现在在一个新的终端运行命令: 'go run main/dpos.go -l %d -d %s '", listenPort+1, fullAddr) 84 | } 85 | return basicHost, nil 86 | } 87 | 88 | func HandleStream(s net.Stream) { 89 | log.Println("得到一个新的连接!", s.Conn().RemotePeer().Pretty()) 90 | // 将连接加入到 91 | rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s)) 92 | go readData(rw) 93 | go writeData(rw) 94 | } 95 | 96 | func readData(rw *bufio.ReadWriter) { 97 | for { 98 | str, err := rw.ReadString('\n') 99 | if err != nil { 100 | log.Fatal(err) 101 | } 102 | 103 | if str == "" { 104 | return 105 | } 106 | if str != "\n" { 107 | chain := make([]Block, 0) 108 | 109 | if err := json.Unmarshal([]byte(str), &chain); err != nil { 110 | log.Fatal(err) 111 | } 112 | 113 | mutex.Lock() 114 | if len(chain) > len(BlockChain) { 115 | BlockChain = chain 116 | bytes, err := json.MarshalIndent(BlockChain, "", " ") 117 | if err != nil { 118 | log.Fatal(err) 119 | } 120 | 121 | fmt.Printf("\x1b[32m%s\x1b[0m> ", string(bytes)) 122 | } 123 | mutex.Unlock() 124 | } 125 | } 126 | } 127 | 128 | func writeData(rw *bufio.ReadWriter) { 129 | // 启动一个协程处理终端同步 130 | go func() { 131 | for { 132 | time.Sleep(2 * time.Second) 133 | mutex.Lock() 134 | bytes, err := json.Marshal(BlockChain) 135 | if err != nil { 136 | log.Println(err) 137 | } 138 | mutex.Unlock() 139 | 140 | mutex.Lock() 141 | rw.WriteString(fmt.Sprintf("%s\n", string(bytes))) 142 | rw.Flush() 143 | mutex.Unlock() 144 | } 145 | }() 146 | 147 | stdReader := bufio.NewReader(os.Stdin) 148 | for { 149 | fmt.Print(">") 150 | sendData, err := stdReader.ReadString('\n') 151 | if err != nil { 152 | log.Fatal(err) 153 | } 154 | 155 | sendData = strings.Replace(sendData, "\n", "", -1) 156 | bpm, err := strconv.Atoi(sendData) 157 | if err != nil { 158 | log.Fatal(err) 159 | } 160 | 161 | // pick选择block生产者 162 | address := PickWinner() 163 | log.Printf("******节点%s获得了记账权利******", address) 164 | lastBlock := BlockChain[len(BlockChain)-1] 165 | newBlock, err := GenerateBlock(lastBlock, bpm, address) 166 | if err != nil{ 167 | log.Fatal(err) 168 | } 169 | 170 | if IsBlockValid(newBlock, lastBlock){ 171 | mutex.Lock() 172 | BlockChain = append(BlockChain, newBlock) 173 | mutex.Unlock() 174 | } 175 | 176 | spew.Dump(BlockChain) 177 | 178 | bytes, err := json.Marshal(BlockChain) 179 | if err != nil { 180 | log.Println(err) 181 | } 182 | mutex.Lock() 183 | rw.WriteString(fmt.Sprintf("%s\n", string(bytes))) 184 | rw.Flush() 185 | mutex.Unlock() 186 | } 187 | } 188 | 189 | func Run() { 190 | 191 | t := time.Now() 192 | genesisBlock := Block{} 193 | genesisBlock = Block{0, t.String(), 0, CaculateBlockHash(genesisBlock), "", ""} 194 | BlockChain = append(BlockChain, genesisBlock) 195 | 196 | // 命令行传参 197 | listenF := flag.Int("l", 0, "等待节点加入") 198 | target := flag.String("d", "", "连接目标节点") 199 | secio := flag.Bool("secio", false, "打开secio") 200 | seed := flag.Int64("seed", 0, "生产随机数") 201 | flag.Parse() 202 | 203 | if *listenF == 0 { 204 | log.Fatal("请提供一个端口号") 205 | } 206 | 207 | // 构造一个host 监听地址 208 | ha, err := MakeBasicHost(*listenF, *secio, *seed) 209 | if err != nil { 210 | log.Fatal(err) 211 | } 212 | 213 | if *target == "" { 214 | log.Println("等待节点连接...") 215 | ha.SetStreamHandler("/p2p/1.0.0", HandleStream) 216 | select {} 217 | } else { 218 | ha.SetStreamHandler("/p2p/1.0.0", HandleStream) 219 | ipfsaddr, err := ma.NewMultiaddr(*target) 220 | if err != nil { 221 | log.Fatal(err) 222 | } 223 | pid, err := ipfsaddr.ValueForProtocol(ma.P_IPFS) 224 | if err != nil { 225 | log.Fatal(err) 226 | } 227 | 228 | peerid, err := peer.IDB58Decode(pid) 229 | if err != nil { 230 | log.Fatal(err) 231 | } 232 | 233 | targetPeerAddr, _ := ma.NewMultiaddr( 234 | fmt.Sprintf("/ipfs/%s", peer.IDB58Encode(peerid))) 235 | targetAddr := ipfsaddr.Decapsulate(targetPeerAddr) 236 | 237 | // 现在我们有一个peerID和一个targetaddr,所以我们添加它到peerstore中。 让libP2P知道如何连接到它。 238 | ha.Peerstore().AddAddr(peerid, targetAddr, pstore.PermanentAddrTTL) 239 | log.Println("打开Stream") 240 | 241 | // 构建一个新的stream从hostB到hostA 242 | // 使用了相同的/p2p/1.0.0 协议 243 | s, err := ha.NewStream(context.Background(), peerid, "/p2p/1.0.0") 244 | if err != nil { 245 | log.Fatal(err) 246 | } 247 | 248 | rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s)) 249 | 250 | go writeData(rw) 251 | go readData(rw) 252 | select {} 253 | } 254 | } 255 | 256 | func SavePeer(name string) { 257 | vote := DefaultVote // 默认的投票数目 258 | f, err := os.OpenFile(FileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) 259 | if err != nil { 260 | log.Fatal(err) 261 | } 262 | defer f.Close() 263 | 264 | 265 | f.WriteString(name + ":" + strconv.Itoa(vote) + "\n") 266 | 267 | } 268 | -------------------------------------------------------------------------------- /src/dpos/readme.md: -------------------------------------------------------------------------------- 1 | # 实现一个简易的DPOS算法 2 | 3 | 4 | ## 架构设计 5 | - 创建一个P2P连接池 6 | - BlockChain生成 7 | - 节点管理与投票 8 | - 选取节点生成区块 9 | - 区块上链 10 | 11 | 12 | ## 代码运行 13 | ``` 14 | go run main/dpos.go -l 3000 -secio 15 | ``` 16 | 17 | ## 投票 18 | ``` 19 | go run main/vote.go -name aaa -v 30 20 | ``` -------------------------------------------------------------------------------- /src/dpos/tools/vote.go: -------------------------------------------------------------------------------- 1 | package tools 2 | 3 | import ( 4 | "flag" 5 | "log" 6 | "fmt" 7 | "os" 8 | "io/ioutil" 9 | "strings" 10 | "strconv" 11 | "github.com/csunny/argo/src/dpos" 12 | 13 | ) 14 | 15 | func Vote() { 16 | name := flag.String("name", "", "节点名称") 17 | vote := flag.Int("v", 0, "投票数量") 18 | flag.Parse() 19 | 20 | if *name == "" { 21 | log.Fatal("节点名称不能为空") 22 | } 23 | 24 | if *vote < 1 { 25 | log.Fatal("最小投票数目为1") 26 | } 27 | 28 | f, err := ioutil.ReadFile(dpos.FileName) 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | 33 | res := strings.Split(string(f), "\n") 34 | 35 | voteMap := make(map[string]string) 36 | for _, node := range res { 37 | nodeSplit := strings.Split(node, ":") 38 | if len(nodeSplit) > 1 { 39 | voteMap[nodeSplit[0]] = fmt.Sprintf("%s", nodeSplit[1]) 40 | } 41 | } 42 | 43 | originVote, err := strconv.Atoi(voteMap[*name]) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | votes := originVote + *vote 48 | voteMap[*name] = fmt.Sprintf("%d", votes) 49 | 50 | log.Printf("节点%s新增票数%d", *name, votes) 51 | str := "" 52 | for k, v := range voteMap { 53 | str += k + ":" + v + "\n" 54 | } 55 | 56 | file, err := os.OpenFile(dpos.FileName, os.O_RDWR, 0666) 57 | file.WriteString(str) 58 | } 59 | -------------------------------------------------------------------------------- /src/graph/dag.go: -------------------------------------------------------------------------------- 1 | package graph 2 | -------------------------------------------------------------------------------- /src/graph/dag_test.go: -------------------------------------------------------------------------------- 1 | package graph 2 | -------------------------------------------------------------------------------- /src/graph/graph.go: -------------------------------------------------------------------------------- 1 | package graph 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // 1. 邻接矩阵表达图的数据结构 8 | // 2. 邻接表(矩阵比较稀疏的时候) V(顶点) E(边) 9 | 10 | // 图的遍历 1. 广度优先 2. 深度优先 11 | 12 | // 广度优先遍历: 从图的某一节点出发,首先依次访问该节点的所有相邻顶点,再按照这些顶点被访问的先后次序,依次访问与它们相邻的所有未被访问的顶点。 13 | // 重复此过程,直到所有的顶点均被访问 14 | 15 | 16 | // 深度优先遍历 17 | // 从图的某个顶点出发访问遍图中所有顶点,且每个顶点仅被访问依次 18 | // DFS 19 | // 1. 访问指定的起始顶点 20 | // 2. 若当前访问的顶点的临接顶点有未被访问的,则任选一个访问,反之,退回到最近访问过的顶点,直到与起始顶点想通的全部顶点都访问完毕 21 | // 3. 若此时图中尚有顶点未被访问, 则选择其中一个顶点作为起始顶点并访问 22 | 23 | type Item interface { 24 | 25 | } 26 | 27 | // 组成图的顶点 28 | type Node struct { 29 | Value Item 30 | } 31 | 32 | // 定义一个图的结构, 图有顶点与边组成 V E 33 | type ItemGraph struct { 34 | Nodes []*Node 35 | Edges map[Node][]*Node 36 | } 37 | 38 | func (n *Node) String() string { 39 | return fmt.Sprintf("%v", n.Value) 40 | } 41 | 42 | // 添加节点 43 | func (g *ItemGraph) AddNode(n *Node) { 44 | g.Nodes = append(g.Nodes, n) 45 | } 46 | 47 | // 添加边 48 | func (g *ItemGraph) AddEdge(n1, n2 *Node) { 49 | if g.Edges == nil{ 50 | g.Edges = make(map[Node][]*Node) 51 | } 52 | 53 | // 无向图 54 | g.Edges[*n1] = append(g.Edges[*n1], n2) // 设定从节点n1到n2的边 55 | g.Edges[*n2] = append(g.Edges[*n2], n1) // 设定从节点n2到n1的边 56 | } 57 | 58 | func (g *ItemGraph) String() { 59 | s := "" 60 | 61 | for i := 0; i< len(g.Nodes); i++{ 62 | s += g.Nodes[i].String() + "->" 63 | near := g.Edges[*g.Nodes[i]] 64 | 65 | for j :=0; j", tdir) 32 | ks, err := NewFSKeystore(tdir) 33 | if err != nil{ 34 | t.Fatal(err) 35 | } 36 | l, err := ks.List() 37 | if err != nil{ 38 | t.Fatal(err) 39 | } 40 | 41 | if len(l) != 0 { 42 | t.Fatal("存在不该有的密钥") 43 | } 44 | k1 := privKeyOrFatal(t) 45 | k2 := privKeyOrFatal(t) 46 | k3 := privKeyOrFatal(t) 47 | k4 := privKeyOrFatal(t) 48 | 49 | err = ks.Put("magic_1", k1) 50 | if err != nil{ 51 | t.Fatal(err) 52 | } 53 | 54 | err = ks.Put("magic_2", k2) 55 | if err != nil{ 56 | t.Fatal(err) 57 | } 58 | 59 | l, err = ks.List() 60 | if err != nil{ 61 | t.Fatal(err) 62 | } 63 | sort.Strings(l) 64 | if l[0] != "magic_1" || l[2] != "magic_2"{ 65 | t.Fatal("密钥列表异常") 66 | } 67 | if err := assertDirContents(tdir, []string{"magic_1", "magic_2"}); err != nil{ 68 | t.Fatal(err) 69 | } 70 | 71 | err = ks.Put("magic_1", k3) 72 | if err != nil{ 73 | t.Fatal("不能重写密钥") 74 | } 75 | if err := assertDirContents(tdir, []string{"magic_1", "magic_2"}); err != nil{ 76 | t.Fatal(err) 77 | } 78 | 79 | exist, err := ks.Has("magic_1") 80 | if !exist{ 81 | t.Fatal("密钥magic_1应该存在") 82 | } 83 | if err != nil{ 84 | t.Fatal(err) 85 | } 86 | exist, err = ks.Has("xxxx") 87 | if exist{ 88 | t.Fatal("密钥xxxx不应该存在") 89 | } 90 | if err != nil{ 91 | t.Fatal(err) 92 | } 93 | if err := ks.Delete("magic_1"); err != nil{ 94 | t.Fatal(err) 95 | } 96 | 97 | if err := assertDirContents(tdir, []string{"magic_2"}); err != nil{ 98 | t.Fatal(err) 99 | } 100 | 101 | if err := ks.Put("magic_3", k3); err != nil{ 102 | t.Fatal(err) 103 | } 104 | if err := ks.Put("magic_4", k4); err != nil{ 105 | t.Fatal(err) 106 | } 107 | 108 | if err := assertDirContents(tdir, []string{"magic_2", "magic_3", "magic_4"}); err != nil{ 109 | t.Fatal(err) 110 | } 111 | if err := assertGetKey(ks, "magic_2", k2); err != nil{ 112 | t.Fatal(err) 113 | } 114 | if err := assertGetKey(ks, "magic_3", k3); err != nil{ 115 | t.Fatal(err) 116 | } 117 | if err := assertGetKey(ks, "magic_4", k4); err != nil{ 118 | t.Fatal(err) 119 | } 120 | 121 | } 122 | 123 | func assertDirContents(dir string, exp []string) error{ 124 | finfos, err := ioutil.ReadDir(dir) 125 | if err != nil{ 126 | return err 127 | } 128 | 129 | if len(finfos) != len(exp){ 130 | return fmt.Errorf("excepted %d directory entries", len(exp)) 131 | } 132 | var names []string 133 | for _, fi := range finfos{ 134 | names = append(names, fi.Name()) 135 | } 136 | 137 | sort.Strings(names) 138 | sort.Strings(exp) 139 | if len(names) != len(exp){ 140 | return fmt.Errorf("文件列表数量异常") 141 | } 142 | for i, v := range names{ 143 | if v != exp[i]{ 144 | return fmt.Errorf("文件有异常的输入") 145 | } 146 | } 147 | return nil 148 | } 149 | 150 | func assertGetKey(ks Keystore, name string, exp ci.PrivKey) error{ 151 | out_k, err := ks.Get(name) 152 | if err != nil{ 153 | return err 154 | } 155 | 156 | if !out_k.Equals(exp){ 157 | return fmt.Errorf("获取到的密钥跟预期的不匹配") 158 | } 159 | return nil 160 | } -------------------------------------------------------------------------------- /src/ipfs/keystore/memkeystore.go: -------------------------------------------------------------------------------- 1 | package keystore 2 | 3 | import ci "github.com/libp2p/go-libp2p-crypto" 4 | 5 | // MemKeystore 是内存存储 6 | type MemKeystore struct{ 7 | keys map[string]ci.PrivKey 8 | } 9 | 10 | // NewMemKeystore 创建hash表来存储key值 11 | func NewMemKeystore() *MemKeystore{ 12 | return &MemKeystore{make(map[string]ci.PrivKey)} 13 | } 14 | 15 | // Has return exists 16 | // TODO need to implement interface api -------------------------------------------------------------------------------- /src/ipfs/keystore/readme.md: -------------------------------------------------------------------------------- 1 | # This the implement of ipfs keystore. 2 | # keystore is a module which store the key 3 | # we can store key in the mem or disk -------------------------------------------------------------------------------- /src/ipfs/readme.md: -------------------------------------------------------------------------------- 1 | # IPFS 2 | 3 | ## 0.1 - Quick Start 4 | 5 | This is a set of short examples with minimal explanation. It is meant as 6 | a "quick start". 7 | 8 | 9 | Add a file to ipfs: 10 | 11 | echo "hello world" >hello 12 | ipfs add hello 13 | 14 | 15 | View it: 16 | 17 | ipfs cat 18 | 19 | 20 | Try a directory: 21 | 22 | mkdir foo 23 | mkdir foo/bar 24 | echo "baz" > foo/baz 25 | echo "baz" > foo/bar/baz 26 | ipfs add -r foo 27 | 28 | 29 | View things: 30 | 31 | ipfs ls 32 | ipfs ls /bar 33 | ipfs cat /baz 34 | ipfs cat /bar/baz 35 | ipfs cat /bar 36 | ipfs ls /baz 37 | 38 | 39 | References: 40 | 41 | ipfs refs 42 | ipfs refs -r 43 | ipfs refs --help 44 | 45 | 46 | Get: 47 | 48 | ipfs get -o foo2 49 | diff foo foo2 50 | 51 | 52 | Objects: 53 | 54 | ipfs object get 55 | ipfs object get /foo2 56 | ipfs object --help 57 | 58 | 59 | Pin + GC: 60 | 61 | ipfs pin add 62 | ipfs repo gc 63 | ipfs ls 64 | ipfs pin rm 65 | ipfs repo gc 66 | 67 | 68 | Daemon: 69 | 70 | ipfs daemon (in another terminal) 71 | ipfs id 72 | 73 | 74 | Network: 75 | 76 | (must be online) 77 | ipfs swarm peers 78 | ipfs id 79 | ipfs cat 80 | 81 | 82 | Mount: 83 | 84 | (warning: fuse is finicky!) 85 | ipfs mount 86 | cd /ipfs/ 87 | ls 88 | 89 | 90 | Tool: 91 | 92 | ipfs version 93 | ipfs update 94 | ipfs commands 95 | ipfs config --help 96 | open http://localhost:5001/webui 97 | 98 | 99 | Browse: 100 | 101 | webui: 102 | 103 | http://localhost:5001/webui 104 | 105 | video: 106 | 107 | http://localhost:8080/ipfs/QmVc6zuAneKJzicnJpfrqCH9gSy6bz54JhcypfJYhGUFQu/play#/ipfs/QmTKZgRNwDNZwHtJSjCp6r5FYefzpULfy37JvMt9DwvXse 108 | 109 | images: 110 | 111 | http://localhost:8080/ipfs/QmZpc3HvfjEXvLWGQPWbHk3AjD5j8NEN4gmFN8Jmrd5g83/cs 112 | 113 | markdown renderer app: 114 | 115 | http://localhost:8080/ipfs/QmX7M9CiYXjVeFnkfVGf3y5ixTZ2ACeSGyL1vBJY1HvQPp/mdown 116 | -------------------------------------------------------------------------------- /src/iterator/iterator.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // The iterable package provides several traversal and searching methods. 6 | // It can be used on anything that satisfies the Iterable interface, 7 | // including vector, though certain functions, such as Map, can also be used on 8 | // something that would produce an infinite amount of data. 9 | package iterable 10 | 11 | type Iterable interface { 12 | // Iter should return a fresh channel each time it is called. 13 | Iter() <-chan interface{} 14 | } 15 | 16 | func not(f func(interface{}) bool) func(interface{}) bool { 17 | return func(e interface{}) bool { return !f(e) } 18 | } 19 | 20 | // All tests whether f is true for every element of iter. 21 | func All(iter Iterable, f func(interface{}) bool) bool { 22 | for e := range iter.Iter() { 23 | if !f(e) { 24 | return false 25 | } 26 | } 27 | return true 28 | } 29 | 30 | // Any tests whether f is true for at least one element of iter. 31 | func Any(iter Iterable, f func(interface{}) bool) bool { 32 | return !All(iter, not(f)) 33 | } 34 | 35 | // filteredIterable is a struct that implements Iterable with each element 36 | // passed through a filter. 37 | type filteredIterable struct { 38 | it Iterable 39 | f func(interface{}) bool 40 | } 41 | 42 | func (f *filteredIterable) iterate(out chan<- interface{}) { 43 | for e := range f.it.Iter() { 44 | if f.f(e) { 45 | out <- e 46 | } 47 | } 48 | close(out) 49 | } 50 | 51 | func (f *filteredIterable) Iter() <-chan interface{} { 52 | ch := make(chan interface{}) 53 | go f.iterate(ch) 54 | return ch 55 | } 56 | 57 | // Filter returns an Iterable that returns the elements of iter that satisfy f. 58 | func Filter(iter Iterable, f func(interface{}) bool) Iterable { 59 | return &filteredIterable{iter, f} 60 | } 61 | 62 | // Find returns the first element of iter that satisfies f. 63 | // Returns nil if no such element is found. 64 | func Find(iter Iterable, f func(interface{}) bool) interface{} { 65 | for e := range Filter(iter, f).Iter() { 66 | return e 67 | } 68 | return nil 69 | } 70 | 71 | // Injector is a type representing a function that takes two arguments, 72 | // an accumulated value and an element, and returns the next accumulated value. 73 | // See the Inject function. 74 | type Injector func(interface{}, interface{}) interface{} 75 | 76 | // Inject combines the elements of iter by repeatedly calling f with an 77 | // accumulated value and each element in order. The starting accumulated value 78 | // is initial, and after each call the accumulated value is set to the return 79 | // value of f. For instance, to compute a sum: 80 | // var arr IntArray = []int{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 81 | // sum := iterable.Inject(arr, 0, 82 | // func(ax interface {}, x interface {}) interface {} { 83 | // return ax.(int) + x.(int) }).(int) 84 | func Inject(iter Iterable, initial interface{}, f Injector) interface{} { 85 | acc := initial 86 | for e := range iter.Iter() { 87 | acc = f(acc, e) 88 | } 89 | return acc 90 | } 91 | 92 | // mappedIterable is a helper struct that implements Iterable, returned by Map. 93 | type mappedIterable struct { 94 | it Iterable 95 | f func(interface{}) interface{} 96 | } 97 | 98 | func (m *mappedIterable) iterate(out chan<- interface{}) { 99 | for e := range m.it.Iter() { 100 | out <- m.f(e) 101 | } 102 | close(out) 103 | } 104 | 105 | func (m *mappedIterable) Iter() <-chan interface{} { 106 | ch := make(chan interface{}) 107 | go m.iterate(ch) 108 | return ch 109 | } 110 | 111 | // Map returns an Iterable that returns the result of applying f to each 112 | // element of iter. 113 | func Map(iter Iterable, f func(interface{}) interface{}) Iterable { 114 | return &mappedIterable{iter, f} 115 | } 116 | 117 | // Partition(iter, f) returns Filter(iter, f) and Filter(iter, !f). 118 | func Partition(iter Iterable, f func(interface{}) bool) (Iterable, Iterable) { 119 | return Filter(iter, f), Filter(iter, not(f)) 120 | } 121 | 122 | // A Func is a function that, when called, sends the 123 | // iterable values on a channel. 124 | type Func func(chan<- interface{}) 125 | 126 | // Iter creates and returns a new channel; it starts a 127 | // goroutine running f to send values to the channel. 128 | func (f Func) Iter() <-chan interface{} { 129 | ch := make(chan interface{}) 130 | go f(ch) 131 | return ch 132 | } 133 | 134 | // TakeWhile returns an Iterable that contains elements from iter while f is true. 135 | func TakeWhile(iter Iterable, f func(interface{}) bool) Iterable { 136 | return Func(func(ch chan<- interface{}) { 137 | for v := range iter.Iter() { 138 | if !f(v) { 139 | break 140 | } 141 | ch <- v 142 | } 143 | close(ch) 144 | }) 145 | } 146 | 147 | // Drop returns an Iterable that returns each element of iter after the first n elements. 148 | func Drop(iter Iterable, n int) Iterable { 149 | return Func(func(ch chan<- interface{}) { 150 | m := n 151 | for v := range iter.Iter() { 152 | if m > 0 { 153 | m-- 154 | continue 155 | } 156 | ch <- v 157 | } 158 | close(ch) 159 | }) 160 | } 161 | 162 | // DropWhile returns an Iterable that returns each element of iter after the initial sequence for which f returns true. 163 | func DropWhile(iter Iterable, f func(interface{}) bool) Iterable { 164 | return Func(func(ch chan<- interface{}) { 165 | drop := true 166 | for v := range iter.Iter() { 167 | if drop { 168 | if f(v) { 169 | continue 170 | } 171 | drop = false 172 | } 173 | ch <- v 174 | } 175 | close(ch) 176 | }) 177 | } 178 | -------------------------------------------------------------------------------- /src/libs/kademlia/contract.go: -------------------------------------------------------------------------------- 1 | package kademlia 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Contract struct { 8 | Id NodeID 9 | Address string 10 | } 11 | 12 | func (contract *Contract) String() string { 13 | return fmt.Sprintf("Contract(\"%s\", \"%s\")", contract.Id, contract.Address) 14 | } 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/libs/kademlia/kademlia.go: -------------------------------------------------------------------------------- 1 | package kademlia 2 | 3 | import ( 4 | "net/rpc" 5 | "net" 6 | "fmt" 7 | ) 8 | 9 | type Kademlia struct { 10 | routers *RoutingTable 11 | NetworkId string 12 | } 13 | 14 | type KademliaCore struct { 15 | kad *Kademlia 16 | } 17 | 18 | type RPCHeader struct { 19 | Sender *Contract 20 | networkId string 21 | } 22 | type PingRequest struct { 23 | RPCHeader 24 | } 25 | 26 | type PingResponce struct { 27 | RPCHeader 28 | } 29 | 30 | type FindNodeRequest struct { 31 | RPCHeader 32 | target NodeID 33 | } 34 | 35 | type FindNodeResponse struct { 36 | RPCHeader 37 | contacts []Contract 38 | } 39 | 40 | func NewKademlia(contract *Contract, networkId string) (ret *Kademlia) { 41 | ret = new(Kademlia) 42 | ret.routers = NewRoutingTable(contract) 43 | ret.NetworkId = networkId 44 | return 45 | } 46 | 47 | // rpc server 48 | func (k *Kademlia) Serve() error { 49 | rpc.RegisterName("KademliaCore", &KademliaCore{k}) 50 | 51 | listener, err := net.Listen("tcp", k.routers.node.Address) 52 | 53 | if err != nil { 54 | return err 55 | } 56 | 57 | conn, err := listener.Accept() 58 | fmt.Println(conn.LocalAddr()) 59 | if err != nil { 60 | return err 61 | } 62 | go rpc.ServeConn(conn) 63 | 64 | go fmt.Println(k.routers) 65 | select{} 66 | return nil 67 | } 68 | 69 | // rpc client 70 | func (k *Kademlia) Call(contract *Contract, method string, args, reply interface{}) error { 71 | client, err := rpc.Dial("tcp", contract.Address) 72 | if err != nil { 73 | return err 74 | } 75 | 76 | fmt.Println(method, args) 77 | err = client.Call(method, args, reply) 78 | if err != nil { 79 | return err 80 | } 81 | 82 | fmt.Println("reply:", reply) 83 | 84 | k.routers.Update(contract) 85 | return nil 86 | } 87 | 88 | func (k *Kademlia) sendQuery(node *Contract, target NodeID, done chan []Contract) { 89 | args := FindNodeRequest{RPCHeader{&k.routers.node, k.NetworkId}, target} 90 | reply := FindNodeResponse{} 91 | 92 | err := k.Call(node, "KademliaCore.FindNode", &args, &reply) 93 | if err != nil { 94 | done <- []Contract{} 95 | } 96 | 97 | done <- reply.contacts 98 | 99 | } 100 | 101 | func (k *Kademlia) HandleRPC(request, response *RPCHeader) error { 102 | //if request.networkId != k.NetworkId { 103 | // return fmt.Errorf("Excepted networkID %s, got %s", k.NetworkId, request.networkId) 104 | //} 105 | 106 | if request.Sender != nil { 107 | k.routers.Update(request.Sender) 108 | } 109 | 110 | response.Sender = &k.routers.node 111 | return nil 112 | } 113 | 114 | func (kc *KademliaCore) Ping(args *PingRequest, response *PingResponce) error { 115 | err := kc.kad.HandleRPC(&args.RPCHeader, &response.RPCHeader) 116 | if err != nil { 117 | return err 118 | } 119 | 120 | fmt.Printf("ping from %s", args.RPCHeader) 121 | return nil 122 | } 123 | 124 | func (kc *KademliaCore) FindNode(args *FindNodeRequest, response *FindNodeResponse) error { 125 | err := kc.kad.HandleRPC(&args.RPCHeader, &response.RPCHeader) 126 | 127 | if err != nil { 128 | return err 129 | } 130 | contancts := kc.kad.routers.FindClosest(args.target, BucketSize) 131 | response.contacts = make([]Contract, len(contancts)) 132 | 133 | //for i := 0; i < len(contancts); i++ { 134 | // // todo there is some error,need to update 135 | // // hashtable need to rewrite. 136 | // response.contacts[i] = *contancts[i].(*ContractRecord).node 137 | //} 138 | 139 | return nil 140 | } 141 | -------------------------------------------------------------------------------- /src/libs/kademlia/kademlia_test.go: -------------------------------------------------------------------------------- 1 | package kademlia 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | //func TestKademliaCore_Ping(t *testing.T) { 8 | // currentNode := Contract{NewRandomNodeID(), "localhost:9999"} 9 | // 10 | // k := NewKademlia(¤tNode, "Test") 11 | // k.Serve() 12 | // 13 | // other := Contract{NewRandomNodeID(), "localhost:9999"} 14 | // err := k.Call( 15 | // &other, "KademliaCore.Ping", &PingRequest{RPCHeader{&other, k.NetworkId}}, 16 | // &PingResponce{}, 17 | // ) 18 | // 19 | // //fmt.Println("==================", k.routers) 20 | // if err != nil{ 21 | // t.Error(err) 22 | // } 23 | // 24 | //} 25 | 26 | func TestKademliaCore_FindNode(t *testing.T) { 27 | currentNode := Contract{NewRandomNodeID(), "localhost:9999"} 28 | k := NewKademlia(¤tNode, "Test") 29 | kc := KademliaCore{k} 30 | 31 | var contacts [100]Contract 32 | 33 | for i:=0; i>uint8(7-j))&0x1 != 0 { 62 | return i*8 + j 63 | } 64 | } 65 | } 66 | return IdLength*8 - 1 67 | } 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/libs/kademlia/nodeid_test.go: -------------------------------------------------------------------------------- 1 | package kademlia 2 | 3 | import ( 4 | "testing" 5 | "fmt" 6 | ) 7 | 8 | func TestNodeID(t *testing.T) { 9 | a := NewNodeID("Node1") 10 | b := NewNodeID("Node2") 11 | c := NewNodeID("Node3") 12 | 13 | fmt.Printf("%s %s %s\n", a, b, c) 14 | 15 | d := NewRandomNodeID() 16 | fmt.Println(d) 17 | 18 | if !a.Equals(a){ 19 | t.Fatal("Equals func is wrong!") 20 | } 21 | 22 | if a.Equals(b){ 23 | t.Fatal("Equals func is wrong!") 24 | } 25 | 26 | e := NodeID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19} 27 | f := NodeID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 18} 28 | g := NodeID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1} 29 | 30 | if !e.Xor(f).Equals(g){ 31 | t.Error(a.Xor(b)) 32 | } 33 | 34 | if g.PrefixLen() != 151{ 35 | t.Error("prefixlen is error") 36 | } 37 | 38 | if b.Less(a){ 39 | t.Error("b should more a!") 40 | } 41 | 42 | fmt.Println(e, e.PrefixLen()) 43 | 44 | } -------------------------------------------------------------------------------- /src/libs/kademlia/readme.md: -------------------------------------------------------------------------------- 1 | # contract.go 2 | 3 | # kademlia.go 4 | 5 | # nodeid.go 6 | 7 | # routingtable.go 8 | -------------------------------------------------------------------------------- /src/libs/kademlia/routingtable.go: -------------------------------------------------------------------------------- 1 | package kademlia 2 | 3 | import ( 4 | "container/list" 5 | "fmt" 6 | ) 7 | 8 | const BucketSize = 20 9 | 10 | type RoutingTable struct { 11 | node Contract 12 | buckets [IdLength * 8]*list.List 13 | } 14 | 15 | type ContractRecord struct { 16 | node *Contract 17 | sortKey NodeID 18 | } 19 | 20 | func (rec *ContractRecord) Less(other interface{}) bool { 21 | return rec.sortKey.Less(other.(*ContractRecord).sortKey) 22 | } 23 | 24 | func NewRoutingTable(node *Contract) (ret *RoutingTable) { 25 | ret = new(RoutingTable) 26 | for i := 0; i < IdLength*8; i++ { 27 | ret.buckets[i] = list.New() 28 | } 29 | ret.node = *node 30 | return 31 | } 32 | 33 | func (table *RoutingTable) Update(contract *Contract) { 34 | prefixLength := contract.Id.Xor(table.node.Id).PrefixLen() 35 | bucket := table.buckets[prefixLength] 36 | 37 | var element interface{} 38 | 39 | iter := bucket.Front() 40 | 41 | for iter != nil { 42 | if Equal(iter.Value, table) == true { 43 | element = bucket.Front() 44 | } else { 45 | iter = bucket.Front().Prev() 46 | } 47 | } 48 | 49 | iterBack := bucket.Back() 50 | for iterBack != nil { 51 | if Equal(iterBack.Value, table) == true { 52 | element = bucket.Back() 53 | } else { 54 | iterBack = bucket.Back().Next() 55 | } 56 | } 57 | 58 | if element == nil { 59 | fmt.Println("-------") 60 | if bucket.Len() < BucketSize { 61 | bucket.PushFront(contract) 62 | } 63 | fmt.Println(bucket.Front().Value) 64 | // 剔除节点 65 | // todo list 66 | 67 | } else { 68 | bucket.MoveToFront(element.(*list.Element)) 69 | } 70 | 71 | } 72 | 73 | func Equal(x interface{}, table *RoutingTable) bool { 74 | return x.(*Contract).Id.Equals(table.node.Id) 75 | } 76 | 77 | func (table *RoutingTable) FindClosest(target NodeID, count int) (ret []interface{}) { 78 | 79 | bucketNum := target.Xor(table.node.Id).PrefixLen() 80 | bucket := table.buckets[bucketNum] 81 | 82 | ret = append(ret, bucket.Front()) 83 | 84 | for i := 1; (bucketNum-i >= 0 || bucketNum+i < IdLength*8) && len(ret) < count; i++ { 85 | if bucketNum-i >= 0 { 86 | bucket = table.buckets[bucketNum-i] 87 | ret = append(ret, bucket.Front()) 88 | } 89 | if bucketNum+i < IdLength*8 { 90 | bucket = table.buckets[bucketNum+i] 91 | ret = append(ret, bucket.Front()) 92 | } 93 | } 94 | 95 | if len(ret) > count { 96 | ret = ret[:count] 97 | } 98 | return 99 | } 100 | -------------------------------------------------------------------------------- /src/libs/kademlia/routingtable_test.go: -------------------------------------------------------------------------------- 1 | package kademlia 2 | 3 | import ( 4 | "testing" 5 | "fmt" 6 | ) 7 | 8 | func TestNewRoutingTable(t *testing.T) { 9 | n1 := NewNodeID("FFFFFFFF") 10 | n2 := NewNodeID("FFFFFFF0") 11 | n3 := NewNodeID("11111111") 12 | 13 | rt := NewRoutingTable(&Contract{n1, "localhost:5000"}) 14 | rt.Update(&Contract{n2, "localhost:5001"}) 15 | rt.Update(&Contract{n3, "localhost:5002"}) 16 | 17 | //fmt.Println(rt) 18 | n4 := NewNodeID("22222222") 19 | res := rt.FindClosest(n4, 2) 20 | 21 | for _, r := range res{ 22 | fmt.Println(r) 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /src/libs/raft/readme.md: -------------------------------------------------------------------------------- 1 | # raft algorithimo 2 | [raft](http://thesecretlivesofdata.com/raft/) 3 | 4 | [zookeeper](https://www.w3cschool.cn/zookeeper/zookeeper_overview.html) 5 | 6 | In this lib we will implement a simple raft algorithm . 7 | 8 | 功能清单: 9 | - Log Replication 10 | - Leader election 11 | - Configuration changes 12 | - Log compaction 13 | - Unit tests 14 | - Fast protobuf Log Encoding 15 | - Http transport 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/libs/zk/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | zk1: 4 | image: zookeeper 5 | container_name: zk1 6 | ports: 7 | - "2181:2181" 8 | environment: 9 | ZOO_MY_ID: 1 10 | ZOO_SERVERS: server.1=zk1:2888:3888 server.2=zk2:2888:3888 server.3=zk3:2888:3888 11 | 12 | zk2: 13 | image: zookeeper 14 | container_name: zk2 15 | ports: 16 | - "2182:2181" 17 | environment: 18 | ZOO_MY_ID: 2 19 | ZOO_SERVERS: server.1=zk1:2888:3888 server.2=zk2:2888:3888 server.3=zk3:2888:3888 20 | 21 | 22 | zk3: 23 | image: zookeeper 24 | container_name: zk3 25 | ports: 26 | - "2183:2181" 27 | environment: 28 | ZOO_MY_ID: 3 29 | ZOO_SERVERS: server.1=zk1:2888:3888 server.2=zk2:2888:3888 server.3=zk3:2888:3888 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/libs/zk/readme.md: -------------------------------------------------------------------------------- 1 | COMPOSE_PROJECT_NAME=zk docker-compose up 2 | 3 | -------------------------------------------------------------------------------- /src/linklist/linked_list.go: -------------------------------------------------------------------------------- 1 | package linklist 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | // Item 可以理解为范性,也就是任意的数据类型 9 | type Item interface { 10 | 11 | } 12 | 13 | // 一个节点,除了自身的数据之外,还必须指向下一个节点,尾部节点指向为nil 14 | type LinkNode struct { 15 | Payload Item // Payload 为任意数据类型 16 | Next *LinkNode 17 | } 18 | 19 | type LinkNoder interface { 20 | // go语言接口,在这个接口里面,我们可以定义一系列的方法。 21 | Add(payload Item) 22 | Delete(index int) Item 23 | Insert(index int, payload Item) 24 | GetLength() int 25 | Search(payload Item) int 26 | GetAll(index int) Item 27 | Reverse() *LinkNode 28 | } 29 | 30 | // go语言方法,对比与下面的NewLinkNode,方法可以理解为面向对象里面对象的方法,虽然实现的功能 31 | // 跟函数类似,但是方式是绑定在对象上的,也就是说我们此处的Add是绑定与head这个LinkNode对象的。 32 | // 这个是go语言区别与其他语言的设计方式,也是go语言很重要的一部分。 33 | func (head *LinkNode) Add(payload Item) { 34 | // 这里采用尾部插入的方式,给链表添加元素 35 | point := head 36 | 37 | for point.Next != nil{ 38 | point = point.Next 39 | } 40 | newNode := LinkNode{payload, nil} 41 | point.Next = &newNode 42 | 43 | 44 | // 头部插入 45 | //newNode := LinkNode{payload, nil} 46 | //newNode.Next = head 47 | } 48 | 49 | 50 | // 删除元素,并且返回删除的节点的值 51 | func (head *LinkNode) Delete(index int) Item { 52 | // 边界条件 53 | linkLength := head.GetLength() 54 | 55 | if index < 0 || index > linkLength{ 56 | fmt.Printf("index out of range %d, please check.", linkLength) 57 | return "index out of range, please check." 58 | } 59 | 60 | point := head 61 | for i := 0; i linkLength{ 76 | fmt.Printf("index out of range %d, please", linkLength) 77 | return 78 | } 79 | 80 | point := head 81 | for i:=0; i head.GetLength() -1 { 104 | break 105 | } 106 | 107 | continue 108 | } 109 | } 110 | 111 | // 判断最后一个元素是否匹配 112 | if point.Payload == payload { 113 | return index 114 | } 115 | 116 | return -1 // 不存在时的返回值 117 | } 118 | 119 | 120 | func (head *LinkNode) GetLength() int { 121 | iterator := head 122 | 123 | var length int 124 | for iterator.Next != nil{ 125 | length ++ 126 | iterator = iterator.Next 127 | } 128 | return length 129 | } 130 | 131 | func (head *LinkNode) GetAll() []Item { 132 | dataList := make([]Item, 0, head.GetLength()) 133 | 134 | point := head 135 | for point.Next != nil{ 136 | dataList = append(dataList, point.Payload) 137 | point = point.Next 138 | } 139 | 140 | dataList = append(dataList, point.Payload) 141 | return dataList 142 | } 143 | 144 | // 创建一个新的链表。 函数,对比与上面的方法,函数是没有绑定任何对象的。 145 | // go语言的函数需要指明参数跟返回值,在此函数中,我们的参数是length,返回值是一个LinkNode对象 146 | // 除了绑定之外,函数跟方法并没有什么不同 147 | func NewLinkNode(length int) *LinkNode { 148 | if length <= 0{ 149 | fmt.Printf("链表长度必须大于0") 150 | log.Panic("链表长度必须大于0") 151 | } 152 | var head *LinkNode 153 | 154 | head = &LinkNode{} 155 | 156 | for i := 0; i n || m > head.GetLength() { 20 | panic("m, n value error!") 21 | } 22 | 23 | count := n - m + 1 // 需要反转的节点个数 24 | 25 | var preNode *LinkNode // 起始反转的节点 26 | 27 | result := head 28 | 29 | for i := 0; i < m; i++ { 30 | preNode = head 31 | head = head.Next 32 | } 33 | 34 | modifyTail := head 35 | var newHead *LinkNode 36 | 37 | for j := 0; j <= count; j++ { 38 | next := head.Next 39 | head.Next = newHead 40 | head = next 41 | } 42 | 43 | modifyTail.Next = head 44 | 45 | if preNode != nil { 46 | preNode.Next = newHead 47 | } else { 48 | result = newHead 49 | } 50 | 51 | return result 52 | } 53 | 54 | // 二、计算两个链表的焦点 55 | 56 | // 三、 合并两个排好序的链表 57 | 58 | // 四、 约瑟夫环 59 | func (tail *LinkNode) NewJosphuseRing(num int) *LinkNode { 60 | // 构造一个环 61 | for i := 0; i < num; i++ { 62 | fmt.Printf("%d\n", i) 63 | 64 | if tail.Payload == "" { 65 | tail := LinkNode{Payload: strconv.Itoa(i)} 66 | tail.Next = &tail 67 | fmt.Printf("---%s\n", tail.Payload) 68 | } else { 69 | newNode := LinkNode{Payload: strconv.Itoa(i)} 70 | fmt.Printf("===%s\n", newNode.Payload) 71 | 72 | newNode.Next = tail.Next 73 | tail.Next = &newNode 74 | 75 | tail = &newNode 76 | } 77 | } 78 | 79 | return tail 80 | } 81 | -------------------------------------------------------------------------------- /src/linklist/usage_test.go: -------------------------------------------------------------------------------- 1 | package linklist 2 | 3 | import "testing" 4 | 5 | func TestLinkNode_NewJosphuseRing(t *testing.T) { 6 | head := LinkNode{} 7 | 8 | itertor := head.NewJosphuseRing(5) 9 | t.Error(itertor) 10 | if itertor != nil { 11 | t.Error(itertor.Payload) 12 | itertor = itertor.Next 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/csunny/argo/src/common" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | 11 | start := time.Now().UnixNano() / 1e6 12 | res := common.Fab(45) 13 | 14 | //res := common.Fab_Hash(45) 15 | end := time.Now().UnixNano() / 1e6 16 | 17 | fmt.Printf("结果%d, 计算时间 %d", res, end-start) 18 | 19 | // 邻接矩阵 20 | s := [][]int{ 21 | {0, 1, 1, 1, 0, 0}, 22 | {1, 0, 0, 0, 1, 0}, 23 | {1, 0, 0, 0, 1, 0}, 24 | {1, 0, 0, 0, 0, 0}, 25 | {0, 1, 1, 0, 0, 0}, 26 | {0, 0, 0, 0, 1, 0}, 27 | } 28 | 29 | // 邻接表 30 | r := make(map[string][]string) 31 | r["A"] = []string{"B", "C", "D"} 32 | r["B"] = []string{"A", "E"} 33 | r["C"] = []string{"A", "E"} 34 | r["D"] = []string{"A"} 35 | r["E"] = []string{"B", "C", "F"} 36 | r["F"] = []string{"E"} 37 | 38 | fmt.Println(s) 39 | fmt.Println(r) 40 | } -------------------------------------------------------------------------------- /src/p2p/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/csunny/argo/src/p2p" 5 | ) 6 | 7 | func main() { 8 | p2p.Run() 9 | } -------------------------------------------------------------------------------- /src/p2p/p2p.go: -------------------------------------------------------------------------------- 1 | package p2p 2 | 3 | import ( 4 | "encoding/hex" 5 | "time" 6 | "crypto/sha256" 7 | "sync" 8 | "context" 9 | "fmt" 10 | "log" 11 | "crypto/rand" 12 | "io" 13 | "bufio" 14 | "encoding/json" 15 | "os" 16 | "strings" 17 | "flag" 18 | "strconv" 19 | 20 | mrand "math/rand" 21 | 22 | "github.com/libp2p/go-libp2p-crypto" 23 | "github.com/libp2p/go-libp2p-host" 24 | 25 | "github.com/libp2p/go-libp2p" 26 | ma "github.com/multiformats/go-multiaddr" 27 | "github.com/libp2p/go-libp2p-net" 28 | 29 | "github.com/davecgh/go-spew/spew" 30 | golog "github.com/ipfs/go-log" 31 | gologging "github.com/whyrusleeping/go-logging" 32 | 33 | "github.com/libp2p/go-libp2p-peer" 34 | 35 | pstore "github.com/libp2p/go-libp2p-peerstore" 36 | ) 37 | 38 | var Blockchain []Block 39 | 40 | var mutex = &sync.Mutex{} 41 | 42 | type Block struct { 43 | Index int 44 | Timestamp string 45 | BPM int 46 | Hash string 47 | PrevHash string 48 | } 49 | 50 | // sha256 hashing 51 | func calculateHash(s string) string { 52 | h := sha256.New() 53 | h.Write([]byte(s)) 54 | hashed := h.Sum(nil) 55 | 56 | return hex.EncodeToString(hashed) 57 | } 58 | 59 | func calculateBlockHash(block Block) string { 60 | record := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash 61 | 62 | return calculateHash(record) 63 | } 64 | 65 | func generateBlock(oldBlock Block, BPM int) Block { 66 | var newBlock Block 67 | t := time.Now() 68 | 69 | newBlock.Index = oldBlock.Index + 1 70 | newBlock.BPM = BPM 71 | newBlock.Timestamp = t.String() 72 | newBlock.PrevHash = oldBlock.Hash 73 | newBlock.Hash = calculateBlockHash(newBlock) 74 | 75 | return newBlock 76 | } 77 | 78 | func isBlockValid(newBlock, oldBlock Block) bool { 79 | if oldBlock.Index+1 != newBlock.Index { 80 | return false 81 | } 82 | 83 | if oldBlock.Hash != newBlock.PrevHash { 84 | return false 85 | } 86 | 87 | if calculateBlockHash(newBlock) != newBlock.Hash { 88 | return false 89 | } 90 | 91 | return true 92 | } 93 | 94 | func makeBasicHost(listenPort int, secio bool, randseed int64) (host.Host, error) { 95 | // if the seed is zero, use real cryptographic randomness. Otherwise, use a deterministic randomness source to make generated keys 96 | // stay the same accross multiple runs 97 | 98 | var r io.Reader 99 | 100 | if randseed == 0 { 101 | r = rand.Reader 102 | } else { 103 | r = mrand.New(mrand.NewSource(randseed)) 104 | } 105 | 106 | // Generata a key pair for the host. We will use it 107 | // to obtain a valid host ID. 108 | 109 | priv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r) 110 | 111 | if err != nil { 112 | return nil, err 113 | } 114 | 115 | opts := []libp2p.Option{ 116 | libp2p.ListenAddrStrings(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", listenPort)), 117 | libp2p.Identity(priv), 118 | } 119 | 120 | if !secio { 121 | opts = append(opts, libp2p.NoSecurity) 122 | } 123 | 124 | basicHost, err := libp2p.New(context.Background(), opts...) 125 | if err != nil { 126 | return nil, err 127 | } 128 | 129 | // Build host multiaddress 130 | hostAddr, _ := ma.NewMultiaddr(fmt.Sprintf("/ipfs/%s", basicHost.ID().Pretty())) 131 | 132 | // Now we can build a full multiaddress to reach this host 133 | // by encapsulating both addresses; 134 | 135 | addr := basicHost.Addrs()[0] 136 | fullAddr := addr.Encapsulate(hostAddr) 137 | 138 | log.Printf("I am %s\n", fullAddr) 139 | 140 | if secio { 141 | log.Printf("Now run \" go run main.go -l %d -d %s -secio \" on a different terminal\n", listenPort+1, fullAddr) 142 | } else { 143 | log.Printf("Now run \" go run main.go -l %d -d %s \" on a different terminal\n", listenPort+1, fullAddr) 144 | } 145 | 146 | return basicHost, nil 147 | } 148 | 149 | func handerStream(s net.Stream) { 150 | log.Println("Got a new stream!") 151 | 152 | // Create a buffer stream for non blocking read and write 153 | rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s)) 154 | go readData(rw) 155 | go writeData(rw) 156 | } 157 | 158 | func readData(rw *bufio.ReadWriter) { 159 | for { 160 | str, err := rw.ReadString('\n') 161 | if err != nil { 162 | log.Fatal(err) 163 | } 164 | 165 | if str == "" { 166 | return 167 | } 168 | 169 | if str != "\n" { 170 | chain := make([]Block, 0) 171 | if err := json.Unmarshal([]byte(str), &chain); err != nil { 172 | log.Fatal(err) 173 | } 174 | 175 | mutex.Lock() 176 | if len(chain) > len(Blockchain) { 177 | Blockchain = chain 178 | bytes, err := json.MarshalIndent(Blockchain, "", " ") 179 | if err != nil { 180 | log.Fatal(err) 181 | } 182 | 183 | // Green console color: 184 | // Reset console color 185 | fmt.Printf("\x1b[32m%s\x1b[0m> ", string(bytes)) 186 | } 187 | 188 | mutex.Unlock() 189 | } 190 | } 191 | } 192 | 193 | func writeData(rw *bufio.ReadWriter) { 194 | go func() { 195 | for { 196 | time.Sleep(5 * time.Second) 197 | mutex.Lock() 198 | bytes, err := json.Marshal(Blockchain) 199 | if err != nil { 200 | log.Println(err) 201 | } 202 | 203 | mutex.Unlock() 204 | 205 | mutex.Lock() 206 | rw.WriteString(fmt.Sprintf("%s\n", string(bytes))) 207 | rw.Flush() 208 | mutex.Unlock() 209 | } 210 | }() 211 | 212 | stdReader := bufio.NewReader(os.Stdin) 213 | 214 | for { 215 | fmt.Print(">") 216 | sendData, err := stdReader.ReadString('\n') 217 | if err != nil { 218 | log.Fatal(err) 219 | } 220 | 221 | sendData = strings.Replace(sendData, "\n", "", -1) 222 | bpm, err := strconv.Atoi(sendData) 223 | if err != nil { 224 | log.Fatal(err) 225 | } 226 | 227 | lastBlock := Blockchain[len(Blockchain)-1] 228 | newBlock := generateBlock(lastBlock, bpm) 229 | 230 | if isBlockValid(newBlock, lastBlock) { 231 | mutex.Lock() 232 | Blockchain = append(Blockchain, newBlock) 233 | mutex.Unlock() 234 | } 235 | 236 | bytes, err := json.Marshal(Blockchain) 237 | if err != nil { 238 | log.Println(err) 239 | } 240 | 241 | spew.Dump(Blockchain) 242 | mutex.Lock() 243 | rw.WriteString(fmt.Sprintf("%s\n", string(bytes))) 244 | rw.Flush() 245 | mutex.Unlock() 246 | } 247 | } 248 | 249 | func Run() { 250 | t := time.Now() 251 | 252 | genesisBlock := Block{} 253 | genesisBlock = Block{0, t.String(), 0, calculateBlockHash(genesisBlock), ""} 254 | 255 | Blockchain = append(Blockchain, genesisBlock) 256 | 257 | // Libp2p code uses golog to log messages, They log with different 258 | // string IDs. We can control the verbosity level for all loggers with: 259 | 260 | golog.SetAllLoggers(gologging.INFO) //change to DEBUG for extra info 261 | 262 | // Parse options from the command line 263 | listenF := flag.Int("l", 0, "wait for incoming connections") 264 | target := flag.String("d", "", "target peer to dail") 265 | secio := flag.Bool("secio", false, "enable secio") 266 | seed := flag.Int64("seed", 0, "set random seed for id generation") 267 | flag.Parse() 268 | 269 | if *listenF == 0 { 270 | log.Fatal("Please provide a port to bind on with -l") 271 | } 272 | 273 | // Make a host that listen on the given multiaddress 274 | ha, err := makeBasicHost(*listenF, *secio, *seed) 275 | if err != nil { 276 | log.Fatal(err) 277 | } 278 | 279 | if *target == "" { 280 | log.Println("listening for connections") 281 | // Set a stream handler on host A. /p2p/1.0.0 is 282 | // a user-defined protocol name 283 | ha.SetStreamHandler("/p2p/1.0.0", handerStream) 284 | select {} //hang forever 285 | } else { 286 | ha.SetStreamHandler("/p2p/1.0.0", handerStream) 287 | 288 | // the following code extracts target's peer ID from the 289 | // given multiaddress 290 | 291 | ipfsaddr, err := ma.NewMultiaddr(*target) 292 | if err != nil { 293 | log.Fatal(err) 294 | } 295 | 296 | pid, err := ipfsaddr.ValueForProtocol(ma.P_IPFS) 297 | if err != nil { 298 | log.Fatal(err) 299 | } 300 | 301 | peerid, err := peer.IDB58Decode(pid) 302 | if err != nil { 303 | log.Fatalln(err) 304 | } 305 | 306 | // Decapsulate the /ipfs/ part from the target 307 | // ip4//ipfs/ becames /ip4/ 308 | 309 | targetPeerAddr, _ := ma.NewMultiaddr( 310 | fmt.Sprintf("/ipfs/%s", peer.IDB58Encode(peerid))) 311 | 312 | targetAddr := ipfsaddr.Decapsulate(targetPeerAddr) 313 | 314 | // We have a peer ID and a a targetAddr so we add it to the peerstore 315 | // so LibP2P knows how to contact it 316 | 317 | ha.Peerstore().AddAddr(peerid, targetAddr, pstore.PermanentAddrTTL) 318 | 319 | log.Println("opening a stream") 320 | // make a new stream from the host B to host A 321 | // it should be handled on host A by the handler we set above bacause 322 | // we use the same /p2p/1.0.0 protocol 323 | s, err := ha.NewStream(context.Background(), peerid, "/p2p/1.0.0") 324 | if err != nil { 325 | log.Fatalln(err) 326 | } 327 | 328 | // Create a buffered stream so that read and writes are non blocking. 329 | rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s)) 330 | 331 | go writeData(rw) 332 | go readData(rw) 333 | 334 | select {} // hang forever 335 | 336 | } 337 | } 338 | -------------------------------------------------------------------------------- /src/p2p/p2p_test.go: -------------------------------------------------------------------------------- 1 | package p2p 2 | -------------------------------------------------------------------------------- /src/p2p/readme.md: -------------------------------------------------------------------------------- 1 | ### Test 2 | 3 | Terminal one 4 | ``` 5 | go run main.go -l 10000 -secio 6 | ``` 7 | 8 | Terminal two 9 | ``` 10 | go run main.go -l 10001 -d /ip4/127.0.0.1/tcp/10000/ipfs/Qmf4X6ypWtb6g1wFFASGgbkUqci5sEA3PYVvgFP81imDR8 -secio 11 | ``` 12 | 13 | Terminal three 14 | ``` 15 | go run main.go -l 10002 -d /ip4/127.0.0.1/tcp/10001/ipfs/QmZrCB3ELTTa1ChjqcyopZ9aRw23Sadt1HFaZ7ZaX4Mrxc -secio 16 | 17 | ``` 18 | 19 | -------------------------------------------------------------------------------- /src/pos/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/csunny/argo/src/pos" 5 | ) 6 | 7 | func main() { 8 | pos.Run() 9 | } 10 | 11 | -------------------------------------------------------------------------------- /src/pos/pos.go: -------------------------------------------------------------------------------- 1 | package pos 2 | 3 | import ( 4 | "sync" 5 | "encoding/hex" 6 | "crypto/sha256" 7 | "time" 8 | "net" 9 | "io" 10 | "bufio" 11 | "strconv" 12 | "log" 13 | "fmt" 14 | "encoding/json" 15 | "math/rand" 16 | "github.com/davecgh/go-spew/spew" 17 | ) 18 | 19 | type Block struct { 20 | Index int 21 | Timestamp string 22 | BPM int 23 | Hash string 24 | PrevHash string 25 | Validator string 26 | } 27 | 28 | // Blockchain is a series of validated Blocks 29 | var Blockchain []Block 30 | var tempBlocks []Block 31 | 32 | // CandidateBlocks handles incoming blocks for validation 33 | var candidateBlocks = make(chan Block) 34 | 35 | // announcements broadcasts winning validator to all nodes 36 | var announcements = make(chan string) 37 | 38 | var mutex = &sync.Mutex{} 39 | 40 | // validators keeps track of open validator and balances 41 | var validators = make(map[string]int) 42 | 43 | // sha256 hashing 44 | 45 | func calculateHash(s string) string { 46 | h := sha256.New() 47 | h.Write([]byte(s)) 48 | hashed := h.Sum(nil) 49 | 50 | return hex.EncodeToString(hashed) 51 | } 52 | 53 | func calculateBlockHash(block Block) string { 54 | record := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash 55 | 56 | return calculateHash(record) 57 | } 58 | 59 | func generateBlock(oldBlock Block, BPM int, address string) (Block, error) { 60 | var newBlock Block 61 | t := time.Now() 62 | 63 | newBlock.Index = oldBlock.Index + 1 64 | newBlock.BPM = BPM 65 | newBlock.Timestamp = t.String() 66 | newBlock.PrevHash = oldBlock.Hash 67 | newBlock.Hash = calculateBlockHash(newBlock) 68 | newBlock.Validator = address 69 | 70 | return newBlock, nil 71 | } 72 | 73 | func isBlockValid(newBlock, oldBlock Block) bool { 74 | if oldBlock.Index+1 != newBlock.Index { 75 | return false 76 | } 77 | 78 | if oldBlock.Hash != newBlock.PrevHash { 79 | return false 80 | } 81 | 82 | if calculateBlockHash(newBlock) != newBlock.Hash { 83 | return false 84 | } 85 | 86 | return true 87 | } 88 | 89 | func handleConn(conn net.Conn) { 90 | defer conn.Close() 91 | 92 | go func() { 93 | for { 94 | msg := <-announcements 95 | io.WriteString(conn, msg) 96 | } 97 | }() 98 | 99 | // validator address 100 | var address string 101 | 102 | // allow user to allocate number of tokens to stake 103 | // the greater the number of tokens, the greater chance to forging a new block 104 | io.WriteString(conn, "Enter token balance:") 105 | scanBalance := bufio.NewScanner(conn) 106 | 107 | // 根据读取到的balance数量,来构建validators的数量 108 | for scanBalance.Scan() { 109 | balance, err := strconv.Atoi(scanBalance.Text()) 110 | if err != nil { 111 | log.Printf("%v not a number: %v", scanBalance.Text(), err) 112 | } 113 | 114 | t := time.Now() 115 | address = calculateHash(t.String()) 116 | validators[address] = balance 117 | 118 | fmt.Println(validators) 119 | break 120 | } 121 | 122 | io.WriteString(conn, "\nEnter a new BPM:") 123 | scanBPM := bufio.NewScanner(conn) 124 | 125 | go func() { 126 | for { 127 | // take in BPM from stdin and add it to blockchain after conducting necessary validation 128 | for scanBPM.Scan() { 129 | bpm, err := strconv.Atoi(scanBPM.Text()) 130 | 131 | // if malicious party 132 | if err != nil { 133 | log.Printf("%v not a number: %v", scanBPM.Text(), err) 134 | delete(validators, address) 135 | conn.Close() 136 | } 137 | 138 | mutex.Lock() 139 | oldLastIndex := Blockchain[len(Blockchain)-1] 140 | mutex.Unlock() 141 | 142 | // create newBlock for consideration to be forged 143 | newBlock, err := generateBlock(oldLastIndex, bpm, address) 144 | if err != nil { 145 | log.Println(err) 146 | continue 147 | } 148 | 149 | spew.Dump(newBlock, oldLastIndex) 150 | 151 | if isBlockValid(newBlock, oldLastIndex) { 152 | candidateBlocks <- newBlock 153 | } 154 | 155 | io.WriteString(conn, "\nEnter a new BPM:") 156 | } 157 | 158 | } 159 | }() 160 | 161 | // simulate receiving broadcast 162 | for { 163 | time.Sleep(time.Minute) 164 | mutex.Lock() 165 | output, err := json.Marshal(Blockchain) 166 | 167 | mutex.Unlock() 168 | if err != nil { 169 | log.Fatal(err) 170 | } 171 | 172 | io.WriteString(conn, string(output)+"\n") 173 | } 174 | } 175 | 176 | // pickWinner creates a lottery pool of validators and chooses the validator who gets to forge a block 177 | // to the blockchain 178 | // by random selecting from the pool, weighted by amount of tokens staked 179 | func PickWinner() { 180 | time.Sleep(10 * time.Second) 181 | mutex.Lock() 182 | 183 | temp := tempBlocks 184 | mutex.Unlock() 185 | 186 | lotteryPool := []string{} 187 | 188 | if len(temp) > 0 { 189 | // slightly modified traditional proof of stake algorithm 190 | // from all validators who submitted a block, weight them by the 191 | // number of staked tokens 192 | // in traditional proof of stake, validators can participate without submitting a block to be forged. 193 | OUTER: 194 | for _, block := range temp { 195 | // if already in lottery pool, skip 196 | for _, node := range lotteryPool { 197 | if block.Validator == node { 198 | continue OUTER 199 | } 200 | } 201 | 202 | // lock list of validators to prevent data race 203 | mutex.Lock() 204 | setValidators := validators 205 | mutex.Unlock() 206 | 207 | k, ok := setValidators[block.Validator] 208 | if ok { 209 | for i := 0; i < k; i++ { 210 | lotteryPool = append(lotteryPool, block.Validator) 211 | } 212 | } 213 | } 214 | 215 | // randomly pick winner from lottery pool 216 | s := rand.NewSource(time.Now().Unix()) 217 | r := rand.New(s) 218 | 219 | lotteryWinner := lotteryPool[r.Intn(len(lotteryPool))] 220 | 221 | // add block of winner to blockchain and let all the other nodes known 222 | for _, block := range temp { 223 | if block.Validator == lotteryWinner { 224 | mutex.Lock() 225 | Blockchain = append(Blockchain, block) 226 | mutex.Unlock() 227 | 228 | for _ = range validators { 229 | announcements <- "\nwinning validator: " + lotteryWinner + "\n" 230 | } 231 | break 232 | } 233 | } 234 | } 235 | 236 | mutex.Lock() 237 | tempBlocks = []Block{} 238 | mutex.Unlock() 239 | } 240 | 241 | // 242 | func Run() { 243 | 244 | // create a genesis block 245 | t := time.Now() 246 | genesisBlock := Block{} 247 | 248 | genesisBlock = Block{0, t.String(), 0, calculateBlockHash(genesisBlock), "", ""} 249 | spew.Dump(genesisBlock) 250 | 251 | Blockchain = append(Blockchain, genesisBlock) 252 | 253 | // start TCP and serve TCP server 254 | server, err := net.Listen("tcp", ":9090") 255 | if err != nil { 256 | log.Fatal(err) 257 | } 258 | 259 | defer server.Close() 260 | 261 | go func() { 262 | for candidate := range candidateBlocks { 263 | mutex.Lock() 264 | tempBlocks = append(tempBlocks, candidate) 265 | mutex.Unlock() 266 | } 267 | }() 268 | 269 | go func() { 270 | for { 271 | PickWinner() 272 | } 273 | }() 274 | 275 | for { 276 | conn, err := server.Accept() 277 | if err != nil { 278 | log.Fatal(err) 279 | } 280 | 281 | go handleConn(conn) 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /src/pos/pos_test.go: -------------------------------------------------------------------------------- 1 | package pos -------------------------------------------------------------------------------- /src/pos/readme.md: -------------------------------------------------------------------------------- 1 | ### Node need todo 2 | - Allow it to enter a token balance 3 | - Receive a broadcast of the latest blockchain 4 | - Receive a broadcast of which validator in the network won the latest block 5 | - Add itself to the overall list of validators 6 | - Enter block data BPM --remember, this is each validator's pulse rate 7 | - Propose a new block 8 | 9 | 10 | 11 | ### Test 12 | 13 | - Use Linux nc command 14 | nc localhost 9090 15 | 16 | - Enter Balance you want to set. 17 | 18 | - BPM use to generate a new block 19 | 20 | 21 | ### Reference 22 | - https://medium.com/@mycoralhealth/code-your-own-proof-of-stake-blockchain-in-go-610cd99aa658 -------------------------------------------------------------------------------- /src/queue/q.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | type Item interface { 4 | } 5 | 6 | // Item the type of the queue 7 | type ItemQueue struct { 8 | items []Item 9 | } 10 | 11 | type ItemQueuer interface { 12 | New() ItemQueue 13 | Enqueue(t Item) 14 | Dequeue() *Item 15 | IsEmpty() bool 16 | Size() int 17 | } 18 | 19 | // New creates a new ItemQueue 20 | func (s *ItemQueue) New() *ItemQueue { 21 | s.items = []Item{} 22 | return s 23 | } 24 | 25 | // Enqueue adds an Item to the end of the queue 26 | func (s *ItemQueue) Enqueue(t Item) { 27 | s.items = append(s.items, t) 28 | } 29 | 30 | // dequeue 31 | func (s *ItemQueue) Dequeue() Item { 32 | item := s.items[0] // 先进先出 33 | s.items = s.items[1:len(s.items)] 34 | 35 | return &item 36 | } 37 | 38 | func (s *ItemQueue) IsEmpty() bool { 39 | return len(s.items) == 0 40 | } 41 | 42 | // Size returns the number of Items in the queue 43 | func (s *ItemQueue) Size() int { 44 | return len(s.items) 45 | } 46 | -------------------------------------------------------------------------------- /src/queue/q_test.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | import "testing" 4 | 5 | var q ItemQueue 6 | 7 | func initQueue() *ItemQueue { 8 | if q.items == nil{ 9 | q = ItemQueue{} 10 | q.New() 11 | } 12 | 13 | return &q 14 | } 15 | 16 | func TestItemQueue_Enqueue(t *testing.T) { 17 | q := initQueue() 18 | q.Enqueue(1) 19 | q.Enqueue(2) 20 | q.Enqueue(3) 21 | 22 | if size := q.Size(); size != 3{ 23 | t.Errorf("wrong count, the correct count is 3 but got %d", size) 24 | } 25 | } 26 | 27 | func TestItemQueue_Dequeue(t *testing.T) { 28 | q.Dequeue() 29 | 30 | if size := q.Size(); size != 2{ 31 | t.Errorf("test failed, the corrected value is 2, but got %d", size) 32 | } 33 | 34 | q.Dequeue() 35 | q.Dequeue() 36 | if !q.IsEmpty(){ 37 | t.Errorf("the queue should be empty.") 38 | } 39 | } -------------------------------------------------------------------------------- /src/stack/stack.go: -------------------------------------------------------------------------------- 1 | package stack 2 | 3 | type Item interface { 4 | } 5 | 6 | // ItemStack the stack of items 7 | type ItemStack struct { 8 | items []Item 9 | } 10 | 11 | // New Create a new ItemStack 12 | func (s *ItemStack) New() *ItemStack { 13 | s.items = []Item{} 14 | return s 15 | } 16 | 17 | // Push adds an Item to the top of the stack 18 | func (s *ItemStack) Push(t Item) { 19 | s.items = append(s.items, t) 20 | } 21 | 22 | // Pop removes an Item from the top of the stack 23 | func (s *ItemStack) Pop() *Item { 24 | item := s.items[len(s.items)-1] // 后进先出 25 | s.items = s.items[0:len(s.items)-1] 26 | return &item 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/stack/stack_test.go: -------------------------------------------------------------------------------- 1 | package stack 2 | 3 | import "testing" 4 | 5 | var s ItemStack 6 | 7 | func initStack() *ItemStack { 8 | if s.items == nil{ 9 | s = ItemStack{} 10 | s.New() 11 | } 12 | 13 | return &s 14 | } 15 | 16 | func TestItemStack_Push(t *testing.T) { 17 | s := initStack() 18 | 19 | s.Push(1) 20 | s.Push(2) 21 | s.Push(3) 22 | 23 | if size := len(s.items); size != 3{ 24 | t.Errorf("test failed ") 25 | } 26 | } 27 | 28 | 29 | func TestItemStack_Pop(t *testing.T) { 30 | s.Pop() 31 | 32 | if size := len(s.items); size !=2 { 33 | t.Errorf("test failed, excepted 2 and got %d", size) 34 | } 35 | 36 | s.Pop() 37 | s.Pop() 38 | 39 | if size := len(s.items); size != 0{ 40 | t.Errorf("test failed, excepted 0 and got %d", size) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/tree/binary_search_tree.go: -------------------------------------------------------------------------------- 1 | // 二叉搜索树 2 | // 前序遍历: 根节点 ——> 左子树 ——> 右子树 3 | // 中序遍历: 左子树 ——> 根节点 ——> 右子树 4 | // 后序遍历: 左子树 ——> 右子树 ——> 根节点 5 | 6 | 7 | package tree 8 | 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | type Item interface { 14 | } 15 | 16 | // 节点 17 | type Node struct { 18 | Key int 19 | Value Item 20 | left *Node 21 | right *Node 22 | } 23 | 24 | // 接下来实现以下方法。 25 | type ItemBinarySearchTreer interface { 26 | Insert(key int, value Item) 27 | Min() *Item 28 | Max() *Item 29 | Search(key int) bool 30 | InOrderTraverse(f func(item Item)) 31 | PreOrderTraverse(f func(item Item)) 32 | PostOrderTraverse(f func(item Item)) 33 | String() 34 | } 35 | 36 | // ItemBinarySearchTree the binary search tree of the Items 37 | type ItemBinarySearchTree struct { 38 | Root *Node 39 | } 40 | 41 | // insert element 42 | func (bst *ItemBinarySearchTree) Insert(key int, value Item) { 43 | n := &Node{key, value, nil, nil} 44 | 45 | if bst.Root == nil{ 46 | bst.Root = n 47 | }else { 48 | // 49 | insertNode(bst.Root, n) 50 | } 51 | } 52 | 53 | func insertNode(node, newNode *Node) { 54 | if newNode.Key < node.Key{ 55 | // 左边插入 56 | if node.left == nil{ 57 | node.left = newNode 58 | }else { 59 | insertNode(node.left, newNode) 60 | } 61 | }else { 62 | if node.right == nil{ 63 | node.right = newNode 64 | }else { 65 | insertNode(node.right, newNode) 66 | } 67 | } 68 | } 69 | 70 | // 最小值,根据二叉搜索树的特性,最小值在树的最左边 71 | func (bst *ItemBinarySearchTree) Min() *Item { 72 | n := bst.Root 73 | 74 | if n == nil{ 75 | return nil 76 | } 77 | 78 | for { 79 | if n.left == nil{ 80 | return &n.Value 81 | } 82 | n = n.left 83 | } 84 | } 85 | 86 | // 最大值,一定在树的最右边 87 | func (bst *ItemBinarySearchTree) Max() *Item { 88 | n := bst.Root 89 | 90 | if n == nil{ 91 | return &n.Value 92 | } 93 | 94 | for { 95 | if n.right == nil{ 96 | return &n.Value 97 | }else { 98 | n = n.right 99 | } 100 | } 101 | } 102 | 103 | // 二叉搜索树,查找元素 104 | func (bst *ItemBinarySearchTree) Search(key int) bool { 105 | return search(bst.Root, key) 106 | } 107 | 108 | func search(n *Node, key int) bool { 109 | if n == nil{ 110 | return false 111 | } 112 | 113 | if key < n.Key{ 114 | return search(n.left, key) 115 | } 116 | 117 | if key > n.Key{ 118 | return search(n.right, key) 119 | } 120 | 121 | return true 122 | } 123 | 124 | // 中序遍历 125 | func (bst *ItemBinarySearchTree) InOrderTraverse(f func(item Item)) { 126 | inOrderTraver(bst.Root, f) 127 | } 128 | 129 | func inOrderTraver(n *Node, f func(item Item)) { 130 | if n != nil{ 131 | inOrderTraver(n.left, f) 132 | f(n.Value) 133 | inOrderTraver(n.right, f) 134 | } 135 | } 136 | 137 | // 前序遍历 138 | func (bst *ItemBinarySearchTree) PreOrderTraverse(f func(item Item)) { 139 | preOrdertraver(bst.Root, f) 140 | } 141 | 142 | func preOrdertraver(n *Node, f func(item Item)) { 143 | if n != nil{ 144 | f(n.Value) 145 | preOrdertraver(n.left, f) 146 | preOrdertraver(n.right, f) 147 | } 148 | } 149 | 150 | // 后序遍历 151 | func (bst *ItemBinarySearchTree) PostOrderTraverse(f func(item Item)) { 152 | postOrderTraver(bst.Root, f) 153 | } 154 | 155 | func postOrderTraver(n *Node, f func(item Item)) { 156 | if n != nil{ 157 | postOrderTraver(n.left, f) 158 | postOrderTraver(n.right, f) 159 | f(n.Value) 160 | } 161 | } 162 | 163 | func (bst *ItemBinarySearchTree) String() { 164 | fmt.Println(" ---------------------------------------------------- ") 165 | stringify(bst.Root, 0) 166 | fmt.Println(" ---------------------------------------------------- ") 167 | } 168 | 169 | func stringify(n *Node, level int) { 170 | if n != nil{ 171 | format := "" 172 | for i:=0; i