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.

350 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. "encoding/base64"
  4. "fmt"
  5. "io/ioutil"
  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. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  16. "github.com/tendermint/tendermint/types"
  17. tmtime "github.com/tendermint/tendermint/types/time"
  18. )
  19. func TestGenLoadValidator(t *testing.T) {
  20. assert := assert.New(t)
  21. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  22. require.Nil(t, err)
  23. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  24. require.Nil(t, err)
  25. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  26. require.NoError(t, err)
  27. height := int64(100)
  28. privVal.LastSignState.Height = height
  29. privVal.Save()
  30. addr := privVal.GetAddress()
  31. privVal = LoadFilePV(tempKeyFile.Name(), tempStateFile.Name())
  32. assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same")
  33. assert.Equal(height, privVal.LastSignState.Height, "expected privval.LastHeight to have been saved")
  34. }
  35. func TestResetValidator(t *testing.T) {
  36. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  37. require.Nil(t, err)
  38. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  39. require.Nil(t, err)
  40. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  41. require.NoError(t, err)
  42. emptyState := FilePVLastSignState{filePath: tempStateFile.Name()}
  43. // new priv val has empty state
  44. assert.Equal(t, privVal.LastSignState, emptyState)
  45. // test vote
  46. height, round := int64(10), int32(1)
  47. voteType := tmproto.PrevoteType
  48. randBytes := tmrand.Bytes(tmhash.Size)
  49. blockID := types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}}
  50. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  51. err = privVal.SignVote("mychainid", vote.ToProto())
  52. assert.NoError(t, err, "expected no error signing vote")
  53. // priv val after signing is not same as empty
  54. assert.NotEqual(t, privVal.LastSignState, emptyState)
  55. // priv val after AcceptNewConnection is same as empty
  56. privVal.Reset()
  57. assert.Equal(t, privVal.LastSignState, emptyState)
  58. }
  59. func TestLoadOrGenValidator(t *testing.T) {
  60. assert := assert.New(t)
  61. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  62. require.Nil(t, err)
  63. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  64. require.Nil(t, err)
  65. tempKeyFilePath := tempKeyFile.Name()
  66. if err := os.Remove(tempKeyFilePath); err != nil {
  67. t.Error(err)
  68. }
  69. tempStateFilePath := tempStateFile.Name()
  70. if err := os.Remove(tempStateFilePath); err != nil {
  71. t.Error(err)
  72. }
  73. privVal, err := LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  74. require.NoError(t, err)
  75. addr := privVal.GetAddress()
  76. privVal, err = LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  77. require.NoError(t, err)
  78. assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same")
  79. }
  80. func TestUnmarshalValidatorState(t *testing.T) {
  81. assert, require := assert.New(t), require.New(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.Nil(err, "%+v", err)
  91. // make sure the values match
  92. assert.EqualValues(val.Height, 1)
  93. assert.EqualValues(val.Round, 1)
  94. assert.EqualValues(val.Step, 1)
  95. // export it and make sure it is the same
  96. out, err := tmjson.Marshal(val)
  97. require.Nil(err, "%+v", err)
  98. assert.JSONEq(serialized, string(out))
  99. }
  100. func TestUnmarshalValidatorKey(t *testing.T) {
  101. assert, require := assert.New(t), require.New(t)
  102. // create some fixed values
  103. privKey := ed25519.GenPrivKey()
  104. pubKey := privKey.PubKey()
  105. addr := pubKey.Address()
  106. pubBytes := pubKey.Bytes()
  107. privBytes := privKey.Bytes()
  108. pubB64 := base64.StdEncoding.EncodeToString(pubBytes)
  109. privB64 := base64.StdEncoding.EncodeToString(privBytes)
  110. serialized := fmt.Sprintf(`{
  111. "address": "%s",
  112. "pub_key": {
  113. "type": "tendermint/PubKeyEd25519",
  114. "value": "%s"
  115. },
  116. "priv_key": {
  117. "type": "tendermint/PrivKeyEd25519",
  118. "value": "%s"
  119. }
  120. }`, addr, pubB64, privB64)
  121. val := FilePVKey{}
  122. err := tmjson.Unmarshal([]byte(serialized), &val)
  123. require.Nil(err, "%+v", err)
  124. // make sure the values match
  125. assert.EqualValues(addr, val.Address)
  126. assert.EqualValues(pubKey, val.PubKey)
  127. assert.EqualValues(privKey, val.PrivKey)
  128. // export it and make sure it is the same
  129. out, err := tmjson.Marshal(val)
  130. require.Nil(err, "%+v", err)
  131. assert.JSONEq(serialized, string(out))
  132. }
  133. func TestSignVote(t *testing.T) {
  134. assert := assert.New(t)
  135. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  136. require.Nil(t, err)
  137. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  138. require.Nil(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("mychainid", v)
  153. assert.NoError(err, "expected no error signing vote")
  154. // try to sign the same vote again; should be fine
  155. err = privVal.SignVote("mychainid", v)
  156. assert.NoError(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. cpb := c.ToProto()
  166. err = privVal.SignVote("mychainid", cpb)
  167. assert.Error(err, "expected error on signing conflicting vote")
  168. }
  169. // try signing a vote with a different time stamp
  170. sig := vote.Signature
  171. vote.Timestamp = vote.Timestamp.Add(time.Duration(1000))
  172. err = privVal.SignVote("mychainid", v)
  173. assert.NoError(err)
  174. assert.Equal(sig, vote.Signature)
  175. }
  176. func TestSignProposal(t *testing.T) {
  177. assert := assert.New(t)
  178. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  179. require.Nil(t, err)
  180. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  181. require.Nil(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("mychainid", pbp)
  195. assert.NoError(err, "expected no error signing proposal")
  196. // try to sign the same proposal again; should be fine
  197. err = privVal.SignProposal("mychainid", pbp)
  198. assert.NoError(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. err = privVal.SignProposal("mychainid", c.ToProto())
  208. assert.Error(err, "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("mychainid", pbp)
  214. assert.NoError(err)
  215. assert.Equal(sig, proposal.Signature)
  216. }
  217. func TestDifferByTimestamp(t *testing.T) {
  218. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  219. require.Nil(t, err)
  220. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  221. require.Nil(t, err)
  222. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  223. require.NoError(t, err)
  224. randbytes := tmrand.Bytes(tmhash.Size)
  225. block1 := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}}
  226. height, round := int64(10), int32(1)
  227. chainID := "mychainid"
  228. // test proposal
  229. {
  230. proposal := newProposal(height, round, block1)
  231. pb := proposal.ToProto()
  232. err := privVal.SignProposal(chainID, pb)
  233. assert.NoError(t, err, "expected no error signing proposal")
  234. signBytes := types.ProposalSignBytes(chainID, pb)
  235. sig := proposal.Signature
  236. timeStamp := proposal.Timestamp
  237. // manipulate the timestamp. should get changed back
  238. pb.Timestamp = pb.Timestamp.Add(time.Millisecond)
  239. var emptySig []byte
  240. proposal.Signature = emptySig
  241. err = privVal.SignProposal("mychainid", pb)
  242. assert.NoError(t, err, "expected no error on signing same proposal")
  243. assert.Equal(t, timeStamp, pb.Timestamp)
  244. assert.Equal(t, signBytes, types.ProposalSignBytes(chainID, pb))
  245. assert.Equal(t, sig, proposal.Signature)
  246. }
  247. // test vote
  248. {
  249. voteType := tmproto.PrevoteType
  250. blockID := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{}}
  251. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  252. v := vote.ToProto()
  253. err := privVal.SignVote("mychainid", v)
  254. assert.NoError(t, err, "expected no error signing vote")
  255. signBytes := types.VoteSignBytes(chainID, v)
  256. sig := v.Signature
  257. timeStamp := vote.Timestamp
  258. // manipulate the timestamp. should get changed back
  259. v.Timestamp = v.Timestamp.Add(time.Millisecond)
  260. var emptySig []byte
  261. v.Signature = emptySig
  262. err = privVal.SignVote("mychainid", v)
  263. assert.NoError(t, err, "expected no error on signing same vote")
  264. assert.Equal(t, timeStamp, v.Timestamp)
  265. assert.Equal(t, signBytes, types.VoteSignBytes(chainID, v))
  266. assert.Equal(t, sig, v.Signature)
  267. }
  268. }
  269. func newVote(addr types.Address, idx int32, height int64, round int32,
  270. typ tmproto.SignedMsgType, blockID types.BlockID) *types.Vote {
  271. return &types.Vote{
  272. ValidatorAddress: addr,
  273. ValidatorIndex: idx,
  274. Height: height,
  275. Round: round,
  276. Type: typ,
  277. Timestamp: tmtime.Now(),
  278. BlockID: blockID,
  279. }
  280. }
  281. func newProposal(height int64, round int32, blockID types.BlockID) *types.Proposal {
  282. return &types.Proposal{
  283. Height: height,
  284. Round: round,
  285. BlockID: blockID,
  286. Timestamp: tmtime.Now(),
  287. }
  288. }