You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

352 lines
11 KiB

privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
  1. package privval
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "os"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. "github.com/tendermint/tendermint/crypto/ed25519"
  12. "github.com/tendermint/tendermint/crypto/tmhash"
  13. tmjson "github.com/tendermint/tendermint/libs/json"
  14. tmrand "github.com/tendermint/tendermint/libs/rand"
  15. tmtime "github.com/tendermint/tendermint/libs/time"
  16. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. func TestGenLoadValidator(t *testing.T) {
  20. tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
  21. require.NoError(t, err)
  22. tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
  23. require.NoError(t, err)
  24. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  25. require.NoError(t, err)
  26. height := int64(100)
  27. privVal.LastSignState.Height = height
  28. require.NoError(t, privVal.Save())
  29. addr := privVal.GetAddress()
  30. privVal, err = LoadFilePV(tempKeyFile.Name(), tempStateFile.Name())
  31. assert.NoError(t, err)
  32. assert.Equal(t, addr, privVal.GetAddress(), "expected privval addr to be the same")
  33. assert.Equal(t, height, privVal.LastSignState.Height, "expected privval.LastHeight to have been saved")
  34. }
  35. func TestResetValidator(t *testing.T) {
  36. ctx, cancel := context.WithCancel(context.Background())
  37. defer cancel()
  38. tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
  39. require.NoError(t, err)
  40. tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
  41. require.NoError(t, err)
  42. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  43. require.NoError(t, err)
  44. emptyState := FilePVLastSignState{filePath: tempStateFile.Name()}
  45. // new priv val has empty state
  46. assert.Equal(t, privVal.LastSignState, emptyState)
  47. // test vote
  48. height, round := int64(10), int32(1)
  49. voteType := tmproto.PrevoteType
  50. randBytes := tmrand.Bytes(tmhash.Size)
  51. blockID := types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}}
  52. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  53. err = privVal.SignVote(ctx, "mychainid", vote.ToProto())
  54. assert.NoError(t, err, "expected no error signing vote")
  55. // priv val after signing is not same as empty
  56. assert.NotEqual(t, privVal.LastSignState, emptyState)
  57. // priv val after AcceptNewConnection is same as empty
  58. require.NoError(t, privVal.Reset())
  59. assert.Equal(t, privVal.LastSignState, emptyState)
  60. }
  61. func TestLoadOrGenValidator(t *testing.T) {
  62. tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
  63. require.NoError(t, err)
  64. tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
  65. require.NoError(t, err)
  66. tempKeyFilePath := tempKeyFile.Name()
  67. if err := os.Remove(tempKeyFilePath); err != nil {
  68. t.Error(err)
  69. }
  70. tempStateFilePath := tempStateFile.Name()
  71. if err := os.Remove(tempStateFilePath); err != nil {
  72. t.Error(err)
  73. }
  74. privVal, err := LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  75. require.NoError(t, err)
  76. addr := privVal.GetAddress()
  77. privVal, err = LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  78. require.NoError(t, err)
  79. assert.Equal(t, addr, privVal.GetAddress(), "expected privval addr to be the same")
  80. }
  81. func TestUnmarshalValidatorState(t *testing.T) {
  82. // create some fixed values
  83. serialized := `{
  84. "height": "1",
  85. "round": 1,
  86. "step": 1
  87. }`
  88. val := FilePVLastSignState{}
  89. err := tmjson.Unmarshal([]byte(serialized), &val)
  90. require.NoError(t, err)
  91. // make sure the values match
  92. assert.EqualValues(t, val.Height, 1)
  93. assert.EqualValues(t, val.Round, 1)
  94. assert.EqualValues(t, val.Step, 1)
  95. // export it and make sure it is the same
  96. out, err := tmjson.Marshal(val)
  97. require.NoError(t, err)
  98. assert.JSONEq(t, serialized, string(out))
  99. }
  100. func TestUnmarshalValidatorKey(t *testing.T) {
  101. // create some fixed values
  102. privKey := ed25519.GenPrivKey()
  103. pubKey := privKey.PubKey()
  104. addr := pubKey.Address()
  105. pubBytes := pubKey.Bytes()
  106. privBytes := privKey.Bytes()
  107. pubB64 := base64.StdEncoding.EncodeToString(pubBytes)
  108. privB64 := base64.StdEncoding.EncodeToString(privBytes)
  109. serialized := fmt.Sprintf(`{
  110. "address": "%s",
  111. "pub_key": {
  112. "type": "tendermint/PubKeyEd25519",
  113. "value": "%s"
  114. },
  115. "priv_key": {
  116. "type": "tendermint/PrivKeyEd25519",
  117. "value": "%s"
  118. }
  119. }`, addr, pubB64, privB64)
  120. val := FilePVKey{}
  121. err := tmjson.Unmarshal([]byte(serialized), &val)
  122. require.NoError(t, err)
  123. // make sure the values match
  124. assert.EqualValues(t, addr, val.Address)
  125. assert.EqualValues(t, pubKey, val.PubKey)
  126. assert.EqualValues(t, privKey, val.PrivKey)
  127. // export it and make sure it is the same
  128. out, err := tmjson.Marshal(val)
  129. require.NoError(t, err)
  130. assert.JSONEq(t, serialized, string(out))
  131. }
  132. func TestSignVote(t *testing.T) {
  133. ctx, cancel := context.WithCancel(context.Background())
  134. defer cancel()
  135. tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
  136. require.NoError(t, err)
  137. tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
  138. require.NoError(t, err)
  139. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  140. require.NoError(t, err)
  141. randbytes := tmrand.Bytes(tmhash.Size)
  142. randbytes2 := tmrand.Bytes(tmhash.Size)
  143. block1 := types.BlockID{Hash: randbytes,
  144. PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}}
  145. block2 := types.BlockID{Hash: randbytes2,
  146. PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}}
  147. height, round := int64(10), int32(1)
  148. voteType := tmproto.PrevoteType
  149. // sign a vote for first time
  150. vote := newVote(privVal.Key.Address, 0, height, round, voteType, block1)
  151. v := vote.ToProto()
  152. err = privVal.SignVote(ctx, "mychainid", v)
  153. assert.NoError(t, err, "expected no error signing vote")
  154. // try to sign the same vote again; should be fine
  155. err = privVal.SignVote(ctx, "mychainid", v)
  156. assert.NoError(t, err, "expected no error on signing same vote")
  157. // now try some bad votes
  158. cases := []*types.Vote{
  159. newVote(privVal.Key.Address, 0, height, round-1, voteType, block1), // round regression
  160. newVote(privVal.Key.Address, 0, height-1, round, voteType, block1), // height regression
  161. newVote(privVal.Key.Address, 0, height-2, round+4, voteType, block1), // height regression and different round
  162. newVote(privVal.Key.Address, 0, height, round, voteType, block2), // different block
  163. }
  164. for _, c := range cases {
  165. assert.Error(t, privVal.SignVote(ctx, "mychainid", c.ToProto()),
  166. "expected error on signing conflicting vote")
  167. }
  168. // try signing a vote with a different time stamp
  169. sig := vote.Signature
  170. vote.Timestamp = vote.Timestamp.Add(time.Duration(1000))
  171. err = privVal.SignVote(ctx, "mychainid", v)
  172. assert.NoError(t, err)
  173. assert.Equal(t, sig, vote.Signature)
  174. }
  175. func TestSignProposal(t *testing.T) {
  176. ctx, cancel := context.WithCancel(context.Background())
  177. defer cancel()
  178. tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
  179. require.NoError(t, err)
  180. tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
  181. require.NoError(t, err)
  182. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  183. require.NoError(t, err)
  184. randbytes := tmrand.Bytes(tmhash.Size)
  185. randbytes2 := tmrand.Bytes(tmhash.Size)
  186. block1 := types.BlockID{Hash: randbytes,
  187. PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}}
  188. block2 := types.BlockID{Hash: randbytes2,
  189. PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}}
  190. height, round := int64(10), int32(1)
  191. // sign a proposal for first time
  192. proposal := newProposal(height, round, block1)
  193. pbp := proposal.ToProto()
  194. err = privVal.SignProposal(ctx, "mychainid", pbp)
  195. assert.NoError(t, err, "expected no error signing proposal")
  196. // try to sign the same proposal again; should be fine
  197. err = privVal.SignProposal(ctx, "mychainid", pbp)
  198. assert.NoError(t, err, "expected no error on signing same proposal")
  199. // now try some bad Proposals
  200. cases := []*types.Proposal{
  201. newProposal(height, round-1, block1), // round regression
  202. newProposal(height-1, round, block1), // height regression
  203. newProposal(height-2, round+4, block1), // height regression and different round
  204. newProposal(height, round, block2), // different block
  205. }
  206. for _, c := range cases {
  207. assert.Error(t, privVal.SignProposal(ctx, "mychainid", c.ToProto()),
  208. "expected error on signing conflicting proposal")
  209. }
  210. // try signing a proposal with a different time stamp
  211. sig := proposal.Signature
  212. proposal.Timestamp = proposal.Timestamp.Add(time.Duration(1000))
  213. err = privVal.SignProposal(ctx, "mychainid", pbp)
  214. assert.NoError(t, err)
  215. assert.Equal(t, sig, proposal.Signature)
  216. }
  217. func TestDifferByTimestamp(t *testing.T) {
  218. ctx, cancel := context.WithCancel(context.Background())
  219. defer cancel()
  220. tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
  221. require.NoError(t, err)
  222. tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
  223. require.NoError(t, err)
  224. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  225. require.NoError(t, err)
  226. randbytes := tmrand.Bytes(tmhash.Size)
  227. block1 := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}}
  228. height, round := int64(10), int32(1)
  229. chainID := "mychainid"
  230. // test proposal
  231. {
  232. proposal := newProposal(height, round, block1)
  233. pb := proposal.ToProto()
  234. err := privVal.SignProposal(ctx, chainID, pb)
  235. require.NoError(t, err, "expected no error signing proposal")
  236. signBytes := types.ProposalSignBytes(chainID, pb)
  237. sig := proposal.Signature
  238. timeStamp := proposal.Timestamp
  239. // manipulate the timestamp. should get changed back
  240. pb.Timestamp = pb.Timestamp.Add(time.Millisecond)
  241. var emptySig []byte
  242. proposal.Signature = emptySig
  243. err = privVal.SignProposal(ctx, "mychainid", pb)
  244. require.NoError(t, err, "expected no error on signing same proposal")
  245. assert.Equal(t, timeStamp, pb.Timestamp)
  246. assert.Equal(t, signBytes, types.ProposalSignBytes(chainID, pb))
  247. assert.Equal(t, sig, proposal.Signature)
  248. }
  249. // test vote
  250. {
  251. voteType := tmproto.PrevoteType
  252. blockID := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{}}
  253. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  254. v := vote.ToProto()
  255. err := privVal.SignVote(ctx, "mychainid", v)
  256. require.NoError(t, err, "expected no error signing vote")
  257. signBytes := types.VoteSignBytes(chainID, v)
  258. sig := v.Signature
  259. timeStamp := vote.Timestamp
  260. // manipulate the timestamp. should get changed back
  261. v.Timestamp = v.Timestamp.Add(time.Millisecond)
  262. var emptySig []byte
  263. v.Signature = emptySig
  264. err = privVal.SignVote(ctx, "mychainid", v)
  265. require.NoError(t, err, "expected no error on signing same vote")
  266. assert.Equal(t, timeStamp, v.Timestamp)
  267. assert.Equal(t, signBytes, types.VoteSignBytes(chainID, v))
  268. assert.Equal(t, sig, v.Signature)
  269. }
  270. }
  271. func newVote(addr types.Address, idx int32, height int64, round int32,
  272. typ tmproto.SignedMsgType, blockID types.BlockID) *types.Vote {
  273. return &types.Vote{
  274. ValidatorAddress: addr,
  275. ValidatorIndex: idx,
  276. Height: height,
  277. Round: round,
  278. Type: typ,
  279. Timestamp: tmtime.Now(),
  280. BlockID: blockID,
  281. }
  282. }
  283. func newProposal(height int64, round int32, blockID types.BlockID) *types.Proposal {
  284. return &types.Proposal{
  285. Height: height,
  286. Round: round,
  287. BlockID: blockID,
  288. Timestamp: tmtime.Now(),
  289. }
  290. }