accounting_simulation_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package protocols
  17. import (
  18. "context"
  19. "flag"
  20. "fmt"
  21. "io/ioutil"
  22. "math/rand"
  23. "os"
  24. "path/filepath"
  25. "reflect"
  26. "sync"
  27. "testing"
  28. "time"
  29. "github.com/mattn/go-colorable"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/rpc"
  32. "github.com/ethereum/go-ethereum/node"
  33. "github.com/ethereum/go-ethereum/p2p"
  34. "github.com/ethereum/go-ethereum/p2p/enode"
  35. "github.com/ethereum/go-ethereum/p2p/simulations"
  36. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  37. )
  38. const (
  39. content = "123456789"
  40. )
  41. var (
  42. nodes = flag.Int("nodes", 30, "number of nodes to create (default 30)")
  43. msgs = flag.Int("msgs", 100, "number of messages sent by node (default 100)")
  44. loglevel = flag.Int("loglevel", 0, "verbosity of logs")
  45. rawlog = flag.Bool("rawlog", false, "remove terminal formatting from logs")
  46. )
  47. func init() {
  48. flag.Parse()
  49. log.PrintOrigins(true)
  50. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(!*rawlog))))
  51. }
  52. //TestAccountingSimulation runs a p2p/simulations simulation
  53. //It creates a *nodes number of nodes, connects each one with each other,
  54. //then sends out a random selection of messages up to *msgs amount of messages
  55. //from the test protocol spec.
  56. //The spec has some accounted messages defined through the Prices interface.
  57. //The test does accounting for all the message exchanged, and then checks
  58. //that every node has the same balance with a peer, but with opposite signs.
  59. //Balance(AwithB) = 0 - Balance(BwithA) or Abs|Balance(AwithB)| == Abs|Balance(BwithA)|
  60. func TestAccountingSimulation(t *testing.T) {
  61. //setup the balances objects for every node
  62. bal := newBalances(*nodes)
  63. //setup the metrics system or tests will fail trying to write metrics
  64. dir, err := ioutil.TempDir("", "account-sim")
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. defer os.RemoveAll(dir)
  69. SetupAccountingMetrics(1*time.Second, filepath.Join(dir, "metrics.db"))
  70. //define the node.Service for this test
  71. services := adapters.Services{
  72. "accounting": func(ctx *adapters.ServiceContext) (node.Service, error) {
  73. return bal.newNode(), nil
  74. },
  75. }
  76. //setup the simulation
  77. adapter := adapters.NewSimAdapter(services)
  78. net := simulations.NewNetwork(adapter, &simulations.NetworkConfig{DefaultService: "accounting"})
  79. defer net.Shutdown()
  80. // we send msgs messages per node, wait for all messages to arrive
  81. bal.wg.Add(*nodes * *msgs)
  82. trigger := make(chan enode.ID)
  83. go func() {
  84. // wait for all of them to arrive
  85. bal.wg.Wait()
  86. // then trigger a check
  87. // the selected node for the trigger is irrelevant,
  88. // we just want to trigger the end of the simulation
  89. trigger <- net.Nodes[0].ID()
  90. }()
  91. // create nodes and start them
  92. for i := 0; i < *nodes; i++ {
  93. conf := adapters.RandomNodeConfig()
  94. bal.id2n[conf.ID] = i
  95. if _, err := net.NewNodeWithConfig(conf); err != nil {
  96. t.Fatal(err)
  97. }
  98. if err := net.Start(conf.ID); err != nil {
  99. t.Fatal(err)
  100. }
  101. }
  102. // fully connect nodes
  103. for i, n := range net.Nodes {
  104. for _, m := range net.Nodes[i+1:] {
  105. if err := net.Connect(n.ID(), m.ID()); err != nil {
  106. t.Fatal(err)
  107. }
  108. }
  109. }
  110. // empty action
  111. action := func(ctx context.Context) error {
  112. return nil
  113. }
  114. // check always checks out
  115. check := func(ctx context.Context, id enode.ID) (bool, error) {
  116. return true, nil
  117. }
  118. // run simulation
  119. timeout := 30 * time.Second
  120. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  121. defer cancel()
  122. result := simulations.NewSimulation(net).Run(ctx, &simulations.Step{
  123. Action: action,
  124. Trigger: trigger,
  125. Expect: &simulations.Expectation{
  126. Nodes: []enode.ID{net.Nodes[0].ID()},
  127. Check: check,
  128. },
  129. })
  130. if result.Error != nil {
  131. t.Fatal(result.Error)
  132. }
  133. // check if balance matrix is symmetric
  134. if err := bal.symmetric(); err != nil {
  135. t.Fatal(err)
  136. }
  137. }
  138. // matrix is a matrix of nodes and its balances
  139. // matrix is in fact a linear array of size n*n,
  140. // so the balance for any node A with B is at index
  141. // A*n + B, while the balance of node B with A is at
  142. // B*n + A
  143. // (n entries in the array will not be filled -
  144. // the balance of a node with itself)
  145. type matrix struct {
  146. n int //number of nodes
  147. m []int64 //array of balances
  148. }
  149. // create a new matrix
  150. func newMatrix(n int) *matrix {
  151. return &matrix{
  152. n: n,
  153. m: make([]int64, n*n),
  154. }
  155. }
  156. // called from the testBalance's Add accounting function: register balance change
  157. func (m *matrix) add(i, j int, v int64) error {
  158. // index for the balance of local node i with remote nodde j is
  159. // i * number of nodes + remote node
  160. mi := i*m.n + j
  161. // register that balance
  162. m.m[mi] += v
  163. return nil
  164. }
  165. // check that the balances are symmetric:
  166. // balance of node i with node j is the same as j with i but with inverted signs
  167. func (m *matrix) symmetric() error {
  168. //iterate all nodes
  169. for i := 0; i < m.n; i++ {
  170. //iterate starting +1
  171. for j := i + 1; j < m.n; j++ {
  172. log.Debug("bal", "1", i, "2", j, "i,j", m.m[i*m.n+j], "j,i", m.m[j*m.n+i])
  173. if m.m[i*m.n+j] != -m.m[j*m.n+i] {
  174. return fmt.Errorf("value mismatch. m[%v, %v] = %v; m[%v, %v] = %v", i, j, m.m[i*m.n+j], j, i, m.m[j*m.n+i])
  175. }
  176. }
  177. }
  178. return nil
  179. }
  180. // all the balances
  181. type balances struct {
  182. i int
  183. *matrix
  184. id2n map[enode.ID]int
  185. wg *sync.WaitGroup
  186. }
  187. func newBalances(n int) *balances {
  188. return &balances{
  189. matrix: newMatrix(n),
  190. id2n: make(map[enode.ID]int),
  191. wg: &sync.WaitGroup{},
  192. }
  193. }
  194. // create a new testNode for every node created as part of the service
  195. func (b *balances) newNode() *testNode {
  196. defer func() { b.i++ }()
  197. return &testNode{
  198. bal: b,
  199. i: b.i,
  200. peers: make([]*testPeer, b.n), //a node will be connected to n-1 peers
  201. }
  202. }
  203. type testNode struct {
  204. bal *balances
  205. i int
  206. lock sync.Mutex
  207. peers []*testPeer
  208. peerCount int
  209. }
  210. // do the accounting for the peer's test protocol
  211. // testNode implements protocols.Balance
  212. func (t *testNode) Add(a int64, p *Peer) error {
  213. //get the index for the remote peer
  214. remote := t.bal.id2n[p.ID()]
  215. log.Debug("add", "local", t.i, "remote", remote, "amount", a)
  216. return t.bal.add(t.i, remote, a)
  217. }
  218. //run the p2p protocol
  219. //for every node, represented by testNode, create a remote testPeer
  220. func (t *testNode) run(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  221. spec := createTestSpec()
  222. //create accounting hook
  223. spec.Hook = NewAccounting(t, &dummyPrices{})
  224. //create a peer for this node
  225. tp := &testPeer{NewPeer(p, rw, spec), t.i, t.bal.id2n[p.ID()], t.bal.wg}
  226. t.lock.Lock()
  227. t.peers[t.bal.id2n[p.ID()]] = tp
  228. t.peerCount++
  229. if t.peerCount == t.bal.n-1 {
  230. //when all peer connections are established, start sending messages from this peer
  231. go t.send()
  232. }
  233. t.lock.Unlock()
  234. return tp.Run(tp.handle)
  235. }
  236. // p2p message receive handler function
  237. func (tp *testPeer) handle(ctx context.Context, msg interface{}) error {
  238. tp.wg.Done()
  239. log.Debug("receive", "from", tp.remote, "to", tp.local, "type", reflect.TypeOf(msg), "msg", msg)
  240. return nil
  241. }
  242. type testPeer struct {
  243. *Peer
  244. local, remote int
  245. wg *sync.WaitGroup
  246. }
  247. func (t *testNode) send() {
  248. log.Debug("start sending")
  249. for i := 0; i < *msgs; i++ {
  250. //determine randomly to which peer to send
  251. whom := rand.Intn(t.bal.n - 1)
  252. if whom >= t.i {
  253. whom++
  254. }
  255. t.lock.Lock()
  256. p := t.peers[whom]
  257. t.lock.Unlock()
  258. //determine a random message from the spec's messages to be sent
  259. which := rand.Intn(len(p.spec.Messages))
  260. msg := p.spec.Messages[which]
  261. switch msg.(type) {
  262. case *perBytesMsgReceiverPays:
  263. msg = &perBytesMsgReceiverPays{Content: content[:rand.Intn(len(content))]}
  264. case *perBytesMsgSenderPays:
  265. msg = &perBytesMsgSenderPays{Content: content[:rand.Intn(len(content))]}
  266. }
  267. log.Debug("send", "from", t.i, "to", whom, "type", reflect.TypeOf(msg), "msg", msg)
  268. p.Send(context.TODO(), msg)
  269. }
  270. }
  271. // define the protocol
  272. func (t *testNode) Protocols() []p2p.Protocol {
  273. return []p2p.Protocol{{
  274. Length: 100,
  275. Run: t.run,
  276. }}
  277. }
  278. func (t *testNode) APIs() []rpc.API {
  279. return nil
  280. }
  281. func (t *testNode) Start(server *p2p.Server) error {
  282. return nil
  283. }
  284. func (t *testNode) Stop() error {
  285. return nil
  286. }