-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathrpc.rs
178 lines (162 loc) · 5.94 KB
/
rpc.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
//! Remote Procedure Calls
// TODO: docs for everything
#![allow(missing_docs)]
use crate::privval::SignableMsg;
use prost::Message as _;
use std::io::Read;
use tendermint::{chain, Proposal, Vote};
use tendermint_p2p::secret_connection::DATA_MAX_SIZE;
use tendermint_proto as proto;
use crate::{
error::{Error, ErrorKind},
prelude::*,
};
/// RPC requests to the KMS
#[derive(Debug)]
pub enum Request {
/// Sign the given message
SignProposal(Proposal),
SignVote(Vote),
ShowPublicKey,
PingRequest,
}
impl Request {
/// Read a request from the given readable.
pub fn read(conn: &mut impl Read, expected_chain_id: &chain::Id) -> Result<Self, Error> {
let mut msg_bytes: Vec<u8> = vec![];
let msg;
// fix for Sei: collect incoming bytes of Protobuf from incoming msg
loop {
let mut msg_chunk = read_msg(conn)?;
let chunk_len = msg_chunk.len();
msg_bytes.append(&mut msg_chunk);
// if we can decode it, great, break the loop
match proto::privval::Message::decode_length_delimited(msg_bytes.as_ref()) {
Ok(m) => {
msg = m.sum;
break;
}
Err(e) => {
// if chunk_len < DATA_MAX_SIZE (1024) we assume it was the end of the message and it is malformed
if chunk_len < DATA_MAX_SIZE {
return Err(format_err!(
ErrorKind::ProtocolError,
"malformed message packet: {}",
e
)
.into());
}
// otherwise, we go to start of the loop assuming next chunk(s)
// will fill the message
}
}
}
let (req, chain_id) = match msg {
Some(proto::privval::message::Sum::SignVoteRequest(
proto::privval::SignVoteRequest {
vote: Some(vote),
chain_id,
},
)) => (Request::SignVote(vote.try_into()?), chain_id),
Some(proto::privval::message::Sum::SignProposalRequest(
proto::privval::SignProposalRequest {
proposal: Some(proposal),
chain_id,
},
)) => (Request::SignProposal(proposal.try_into()?), chain_id),
Some(proto::privval::message::Sum::PubKeyRequest(req)) => {
(Request::ShowPublicKey, req.chain_id)
}
Some(proto::privval::message::Sum::PingRequest(_)) => {
return Ok(Request::PingRequest);
}
_ => fail!(ErrorKind::ProtocolError, "invalid RPC message: {:?}", msg),
};
ensure!(
expected_chain_id == &chain::Id::try_from(chain_id.as_str())?,
ErrorKind::ChainIdError,
"got unexpected chain ID: {} (expecting: {})",
&chain_id,
expected_chain_id
);
Ok(req)
}
/// Convert this request into a [`SignableMsg`].
///
/// The expected `chain::Id` is used to validate the request.
pub fn into_signable_msg(self) -> Result<SignableMsg, Error> {
match self {
Self::SignProposal(proposal) => Ok(proposal.into()),
Self::SignVote(vote) => Ok(vote.into()),
_ => fail!(
ErrorKind::InvalidMessageError,
"expected a signable message type: {:?}",
self
),
}
}
}
/// RPC responses from the KMS
#[derive(Debug)]
pub enum Response {
/// Signature response
SignedVote(proto::privval::SignedVoteResponse),
SignedProposal(proto::privval::SignedProposalResponse),
Ping(proto::privval::PingResponse),
PublicKey(proto::privval::PubKeyResponse),
}
impl Response {
/// Encode response to bytes.
pub fn encode(self) -> Result<Vec<u8>, Error> {
let mut buf = Vec::new();
let msg = match self {
Response::SignedVote(resp) => proto::privval::message::Sum::SignedVoteResponse(resp),
Response::SignedProposal(resp) => {
proto::privval::message::Sum::SignedProposalResponse(resp)
}
Response::Ping(resp) => proto::privval::message::Sum::PingResponse(resp),
Response::PublicKey(resp) => proto::privval::message::Sum::PubKeyResponse(resp),
};
proto::privval::Message { sum: Some(msg) }.encode_length_delimited(&mut buf)?;
Ok(buf)
}
/// Construct an error response for a given [`SignableMsg`].
pub fn error(msg: SignableMsg, error: proto::privval::RemoteSignerError) -> Response {
match msg {
SignableMsg::Proposal(_) => {
Response::SignedProposal(proto::privval::SignedProposalResponse {
proposal: None,
error: Some(error),
})
}
SignableMsg::Vote(_) => Response::SignedVote(proto::privval::SignedVoteResponse {
vote: None,
error: Some(error),
}),
}
}
}
impl From<SignableMsg> for Response {
fn from(msg: SignableMsg) -> Response {
match msg {
SignableMsg::Proposal(proposal) => {
Response::SignedProposal(proto::privval::SignedProposalResponse {
proposal: Some(proposal.into()),
error: None,
})
}
SignableMsg::Vote(vote) => Response::SignedVote(proto::privval::SignedVoteResponse {
vote: Some(vote.into()),
error: None,
}),
}
}
}
/// Read a message from a Secret Connection
// TODO(tarcieri): extract this into Secret Connection
fn read_msg(conn: &mut impl Read) -> Result<Vec<u8>, Error> {
let mut buf = vec![0; DATA_MAX_SIZE];
let buf_read = conn.read(&mut buf)?;
buf.truncate(buf_read);
Ok(buf)
}