accounting_simulation_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. lock sync.Mutex
  149. }
  150. // create a new matrix
  151. func newMatrix(n int) *matrix {
  152. return &matrix{
  153. n: n,
  154. m: make([]int64, n*n),
  155. }
  156. }
  157. // called from the testBalance's Add accounting function: register balance change
  158. func (m *matrix) add(i, j int, v int64) error {
  159. // index for the balance of local node i with remote nodde j is
  160. // i * number of nodes + remote node
  161. mi := i*m.n + j
  162. // register that balance
  163. m.lock.Lock()
  164. m.m[mi] += v
  165. m.lock.Unlock()
  166. return nil
  167. }
  168. // check that the balances are symmetric:
  169. // balance of node i with node j is the same as j with i but with inverted signs
  170. func (m *matrix) symmetric() error {
  171. //iterate all nodes
  172. for i := 0; i < m.n; i++ {
  173. //iterate starting +1
  174. for j := i + 1; j < m.n; j++ {
  175. log.Debug("bal", "1", i, "2", j, "i,j", m.m[i*m.n+j], "j,i", m.m[j*m.n+i])
  176. if m.m[i*m.n+j] != -m.m[j*m.n+i] {
  177. 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])
  178. }
  179. }
  180. }
  181. return nil
  182. }
  183. // all the balances
  184. type balances struct {
  185. i int
  186. *matrix
  187. id2n map[enode.ID]int
  188. wg *sync.WaitGroup
  189. }
  190. func newBalances(n int) *balances {
  191. return &balances{
  192. matrix: newMatrix(n),
  193. id2n: make(map[enode.ID]int),
  194. wg: &sync.WaitGroup{},
  195. }
  196. }
  197. // create a new testNode for every node created as part of the service
  198. func (b *balances) newNode() *testNode {
  199. defer func() { b.i++ }()
  200. return &testNode{
  201. bal: b,
  202. i: b.i,
  203. peers: make([]*testPeer, b.n), //a node will be connected to n-1 peers
  204. }
  205. }
  206. type testNode struct {
  207. bal *balances
  208. i int
  209. lock sync.Mutex
  210. peers []*testPeer
  211. peerCount int
  212. }
  213. // do the accounting for the peer's test protocol
  214. // testNode implements protocols.Balance
  215. func (t *testNode) Add(a int64, p *Peer) error {
  216. //get the index for the remote peer
  217. remote := t.bal.id2n[p.ID()]
  218. log.Debug("add", "local", t.i, "remote", remote, "amount", a)
  219. return t.bal.add(t.i, remote, a)
  220. }
  221. //run the p2p protocol
  222. //for every node, represented by testNode, create a remote testPeer
  223. func (t *testNode) run(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  224. spec := createTestSpec()
  225. //create accounting hook
  226. spec.Hook = NewAccounting(t, &dummyPrices{})
  227. //create a peer for this node
  228. tp := &testPeer{NewPeer(p, rw, spec), t.i, t.bal.id2n[p.ID()], t.bal.wg}
  229. t.lock.Lock()
  230. t.peers[t.bal.id2n[p.ID()]] = tp
  231. t.peerCount++
  232. if t.peerCount == t.bal.n-1 {
  233. //when all peer connections are established, start sending messages from this peer
  234. go t.send()
  235. }
  236. t.lock.Unlock()
  237. return tp.Run(tp.handle)
  238. }
  239. // p2p message receive handler function
  240. func (tp *testPeer) handle(ctx context.Context, msg interface{}) error {
  241. tp.wg.Done()
  242. log.Debug("receive", "from", tp.remote, "to", tp.local, "type", reflect.TypeOf(msg), "msg", msg)
  243. return nil
  244. }
  245. type testPeer struct {
  246. *Peer
  247. local, remote int
  248. wg *sync.WaitGroup
  249. }
  250. func (t *testNode) send() {
  251. log.Debug("start sending")
  252. for i := 0; i < *msgs; i++ {
  253. //determine randomly to which peer to send
  254. whom := rand.Intn(t.bal.n - 1)
  255. if whom >= t.i {
  256. whom++
  257. }
  258. t.lock.Lock()
  259. p := t.peers[whom]
  260. t.lock.Unlock()
  261. //determine a random message from the spec's messages to be sent
  262. which := rand.Intn(len(p.spec.Messages))
  263. msg := p.spec.Messages[which]
  264. switch msg.(type) {
  265. case *perBytesMsgReceiverPays:
  266. msg = &perBytesMsgReceiverPays{Content: content[:rand.Intn(len(content))]}
  267. case *perBytesMsgSenderPays:
  268. msg = &perBytesMsgSenderPays{Content: content[:rand.Intn(len(content))]}
  269. }
  270. log.Debug("send", "from", t.i, "to", whom, "type", reflect.TypeOf(msg), "msg", msg)
  271. p.Send(context.TODO(), msg)
  272. }
  273. }
  274. // define the protocol
  275. func (t *testNode) Protocols() []p2p.Protocol {
  276. return []p2p.Protocol{{
  277. Length: 100,
  278. Run: t.run,
  279. }}
  280. }
  281. func (t *testNode) APIs() []rpc.API {
  282. return nil
  283. }
  284. func (t *testNode) Start(server *p2p.Server) error {
  285. return nil
  286. }
  287. func (t *testNode) Stop() error {
  288. return nil
  289. }