mod.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. use {
  2. crate::{
  3. hash::Hash,
  4. instruction::CompiledInstruction,
  5. message::{legacy::Message as LegacyMessage, v0::MessageAddressTableLookup, MessageHeader},
  6. pubkey::Pubkey,
  7. short_vec,
  8. },
  9. serde::{
  10. de::{self, Deserializer, SeqAccess, Unexpected, Visitor},
  11. ser::{SerializeTuple, Serializer},
  12. },
  13. serde_derive::{Deserialize, Serialize},
  14. solana_sanitize::{Sanitize, SanitizeError},
  15. std::{collections::HashSet, fmt},
  16. };
  17. mod sanitized;
  18. pub mod v0;
  19. pub use sanitized::*;
  20. /// Bit mask that indicates whether a serialized message is versioned.
  21. pub const MESSAGE_VERSION_PREFIX: u8 = 0x80;
  22. /// Either a legacy message or a v0 message.
  23. ///
  24. /// # Serialization
  25. ///
  26. /// If the first bit is set, the remaining 7 bits will be used to determine
  27. /// which message version is serialized starting from version `0`. If the first
  28. /// is bit is not set, all bytes are used to encode the legacy `Message`
  29. /// format.
  30. #[cfg_attr(
  31. feature = "frozen-abi",
  32. frozen_abi(digest = "G4EAiqmGgBprgf5ePYemLJcoFfx4R7rhC1Weo2FVJ7fn"),
  33. derive(AbiEnumVisitor, AbiExample)
  34. )]
  35. #[derive(Debug, PartialEq, Eq, Clone)]
  36. pub enum VersionedMessage {
  37. Legacy(LegacyMessage),
  38. V0(v0::Message),
  39. }
  40. impl VersionedMessage {
  41. pub fn sanitize(&self) -> Result<(), SanitizeError> {
  42. match self {
  43. Self::Legacy(message) => message.sanitize(),
  44. Self::V0(message) => message.sanitize(),
  45. }
  46. }
  47. pub fn header(&self) -> &MessageHeader {
  48. match self {
  49. Self::Legacy(message) => &message.header,
  50. Self::V0(message) => &message.header,
  51. }
  52. }
  53. pub fn static_account_keys(&self) -> &[Pubkey] {
  54. match self {
  55. Self::Legacy(message) => &message.account_keys,
  56. Self::V0(message) => &message.account_keys,
  57. }
  58. }
  59. pub fn address_table_lookups(&self) -> Option<&[MessageAddressTableLookup]> {
  60. match self {
  61. Self::Legacy(_) => None,
  62. Self::V0(message) => Some(&message.address_table_lookups),
  63. }
  64. }
  65. /// Returns true if the account at the specified index signed this
  66. /// message.
  67. pub fn is_signer(&self, index: usize) -> bool {
  68. index < usize::from(self.header().num_required_signatures)
  69. }
  70. /// Returns true if the account at the specified index is writable by the
  71. /// instructions in this message. Since dynamically loaded addresses can't
  72. /// have write locks demoted without loading addresses, this shouldn't be
  73. /// used in the runtime.
  74. pub fn is_maybe_writable(
  75. &self,
  76. index: usize,
  77. reserved_account_keys: Option<&HashSet<Pubkey>>,
  78. ) -> bool {
  79. match self {
  80. Self::Legacy(message) => message.is_maybe_writable(index, reserved_account_keys),
  81. Self::V0(message) => message.is_maybe_writable(index, reserved_account_keys),
  82. }
  83. }
  84. #[deprecated(since = "2.0.0", note = "Please use `is_instruction_account` instead")]
  85. pub fn is_key_passed_to_program(&self, key_index: usize) -> bool {
  86. self.is_instruction_account(key_index)
  87. }
  88. /// Returns true if the account at the specified index is an input to some
  89. /// program instruction in this message.
  90. fn is_instruction_account(&self, key_index: usize) -> bool {
  91. if let Ok(key_index) = u8::try_from(key_index) {
  92. self.instructions()
  93. .iter()
  94. .any(|ix| ix.accounts.contains(&key_index))
  95. } else {
  96. false
  97. }
  98. }
  99. pub fn is_invoked(&self, key_index: usize) -> bool {
  100. match self {
  101. Self::Legacy(message) => message.is_key_called_as_program(key_index),
  102. Self::V0(message) => message.is_key_called_as_program(key_index),
  103. }
  104. }
  105. /// Returns true if the account at the specified index is not invoked as a
  106. /// program or, if invoked, is passed to a program.
  107. pub fn is_non_loader_key(&self, key_index: usize) -> bool {
  108. !self.is_invoked(key_index) || self.is_instruction_account(key_index)
  109. }
  110. pub fn recent_blockhash(&self) -> &Hash {
  111. match self {
  112. Self::Legacy(message) => &message.recent_blockhash,
  113. Self::V0(message) => &message.recent_blockhash,
  114. }
  115. }
  116. pub fn set_recent_blockhash(&mut self, recent_blockhash: Hash) {
  117. match self {
  118. Self::Legacy(message) => message.recent_blockhash = recent_blockhash,
  119. Self::V0(message) => message.recent_blockhash = recent_blockhash,
  120. }
  121. }
  122. /// Program instructions that will be executed in sequence and committed in
  123. /// one atomic transaction if all succeed.
  124. pub fn instructions(&self) -> &[CompiledInstruction] {
  125. match self {
  126. Self::Legacy(message) => &message.instructions,
  127. Self::V0(message) => &message.instructions,
  128. }
  129. }
  130. pub fn serialize(&self) -> Vec<u8> {
  131. bincode::serialize(self).unwrap()
  132. }
  133. /// Compute the blake3 hash of this transaction's message
  134. pub fn hash(&self) -> Hash {
  135. let message_bytes = self.serialize();
  136. Self::hash_raw_message(&message_bytes)
  137. }
  138. /// Compute the blake3 hash of a raw transaction message
  139. pub fn hash_raw_message(message_bytes: &[u8]) -> Hash {
  140. use blake3::traits::digest::Digest;
  141. let mut hasher = blake3::Hasher::new();
  142. hasher.update(b"solana-tx-message-v1");
  143. hasher.update(message_bytes);
  144. Hash(hasher.finalize().into())
  145. }
  146. }
  147. impl Default for VersionedMessage {
  148. fn default() -> Self {
  149. Self::Legacy(LegacyMessage::default())
  150. }
  151. }
  152. impl serde::Serialize for VersionedMessage {
  153. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  154. where
  155. S: Serializer,
  156. {
  157. match self {
  158. Self::Legacy(message) => {
  159. let mut seq = serializer.serialize_tuple(1)?;
  160. seq.serialize_element(message)?;
  161. seq.end()
  162. }
  163. Self::V0(message) => {
  164. let mut seq = serializer.serialize_tuple(2)?;
  165. seq.serialize_element(&MESSAGE_VERSION_PREFIX)?;
  166. seq.serialize_element(message)?;
  167. seq.end()
  168. }
  169. }
  170. }
  171. }
  172. enum MessagePrefix {
  173. Legacy(u8),
  174. Versioned(u8),
  175. }
  176. impl<'de> serde::Deserialize<'de> for MessagePrefix {
  177. fn deserialize<D>(deserializer: D) -> Result<MessagePrefix, D::Error>
  178. where
  179. D: Deserializer<'de>,
  180. {
  181. struct PrefixVisitor;
  182. impl<'de> Visitor<'de> for PrefixVisitor {
  183. type Value = MessagePrefix;
  184. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  185. formatter.write_str("message prefix byte")
  186. }
  187. // Serde's integer visitors bubble up to u64 so check the prefix
  188. // with this function instead of visit_u8. This approach is
  189. // necessary because serde_json directly calls visit_u64 for
  190. // unsigned integers.
  191. fn visit_u64<E: de::Error>(self, value: u64) -> Result<MessagePrefix, E> {
  192. if value > u8::MAX as u64 {
  193. Err(de::Error::invalid_type(Unexpected::Unsigned(value), &self))?;
  194. }
  195. let byte = value as u8;
  196. if byte & MESSAGE_VERSION_PREFIX != 0 {
  197. Ok(MessagePrefix::Versioned(byte & !MESSAGE_VERSION_PREFIX))
  198. } else {
  199. Ok(MessagePrefix::Legacy(byte))
  200. }
  201. }
  202. }
  203. deserializer.deserialize_u8(PrefixVisitor)
  204. }
  205. }
  206. impl<'de> serde::Deserialize<'de> for VersionedMessage {
  207. fn deserialize<D>(deserializer: D) -> Result<VersionedMessage, D::Error>
  208. where
  209. D: Deserializer<'de>,
  210. {
  211. struct MessageVisitor;
  212. impl<'de> Visitor<'de> for MessageVisitor {
  213. type Value = VersionedMessage;
  214. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  215. formatter.write_str("message bytes")
  216. }
  217. fn visit_seq<A>(self, mut seq: A) -> Result<VersionedMessage, A::Error>
  218. where
  219. A: SeqAccess<'de>,
  220. {
  221. let prefix: MessagePrefix = seq
  222. .next_element()?
  223. .ok_or_else(|| de::Error::invalid_length(0, &self))?;
  224. match prefix {
  225. MessagePrefix::Legacy(num_required_signatures) => {
  226. // The remaining fields of the legacy Message struct after the first byte.
  227. #[derive(Serialize, Deserialize)]
  228. struct RemainingLegacyMessage {
  229. pub num_readonly_signed_accounts: u8,
  230. pub num_readonly_unsigned_accounts: u8,
  231. #[serde(with = "short_vec")]
  232. pub account_keys: Vec<Pubkey>,
  233. pub recent_blockhash: Hash,
  234. #[serde(with = "short_vec")]
  235. pub instructions: Vec<CompiledInstruction>,
  236. }
  237. let message: RemainingLegacyMessage =
  238. seq.next_element()?.ok_or_else(|| {
  239. // will never happen since tuple length is always 2
  240. de::Error::invalid_length(1, &self)
  241. })?;
  242. Ok(VersionedMessage::Legacy(LegacyMessage {
  243. header: MessageHeader {
  244. num_required_signatures,
  245. num_readonly_signed_accounts: message.num_readonly_signed_accounts,
  246. num_readonly_unsigned_accounts: message
  247. .num_readonly_unsigned_accounts,
  248. },
  249. account_keys: message.account_keys,
  250. recent_blockhash: message.recent_blockhash,
  251. instructions: message.instructions,
  252. }))
  253. }
  254. MessagePrefix::Versioned(version) => {
  255. match version {
  256. 0 => {
  257. Ok(VersionedMessage::V0(seq.next_element()?.ok_or_else(
  258. || {
  259. // will never happen since tuple length is always 2
  260. de::Error::invalid_length(1, &self)
  261. },
  262. )?))
  263. }
  264. 127 => {
  265. // 0xff is used as the first byte of the off-chain messages
  266. // which corresponds to version 127 of the versioned messages.
  267. // This explicit check is added to prevent the usage of version 127
  268. // in the runtime as a valid transaction.
  269. Err(de::Error::custom("off-chain messages are not accepted"))
  270. }
  271. _ => Err(de::Error::invalid_value(
  272. de::Unexpected::Unsigned(version as u64),
  273. &"a valid transaction message version",
  274. )),
  275. }
  276. }
  277. }
  278. }
  279. }
  280. deserializer.deserialize_tuple(2, MessageVisitor)
  281. }
  282. }
  283. #[cfg(test)]
  284. mod tests {
  285. use {
  286. super::*,
  287. crate::{
  288. instruction::{AccountMeta, Instruction},
  289. message::v0::MessageAddressTableLookup,
  290. },
  291. };
  292. #[test]
  293. fn test_legacy_message_serialization() {
  294. let program_id0 = Pubkey::new_unique();
  295. let program_id1 = Pubkey::new_unique();
  296. let id0 = Pubkey::new_unique();
  297. let id1 = Pubkey::new_unique();
  298. let id2 = Pubkey::new_unique();
  299. let id3 = Pubkey::new_unique();
  300. let instructions = vec![
  301. Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id0, false)]),
  302. Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id1, true)]),
  303. Instruction::new_with_bincode(
  304. program_id1,
  305. &0,
  306. vec![AccountMeta::new_readonly(id2, false)],
  307. ),
  308. Instruction::new_with_bincode(
  309. program_id1,
  310. &0,
  311. vec![AccountMeta::new_readonly(id3, true)],
  312. ),
  313. ];
  314. let mut message = LegacyMessage::new(&instructions, Some(&id1));
  315. message.recent_blockhash = Hash::new_unique();
  316. let wrapped_message = VersionedMessage::Legacy(message.clone());
  317. // bincode
  318. {
  319. let bytes = bincode::serialize(&message).unwrap();
  320. assert_eq!(bytes, bincode::serialize(&wrapped_message).unwrap());
  321. let message_from_bytes: LegacyMessage = bincode::deserialize(&bytes).unwrap();
  322. let wrapped_message_from_bytes: VersionedMessage =
  323. bincode::deserialize(&bytes).unwrap();
  324. assert_eq!(message, message_from_bytes);
  325. assert_eq!(wrapped_message, wrapped_message_from_bytes);
  326. }
  327. // serde_json
  328. {
  329. let string = serde_json::to_string(&message).unwrap();
  330. let message_from_string: LegacyMessage = serde_json::from_str(&string).unwrap();
  331. assert_eq!(message, message_from_string);
  332. }
  333. }
  334. #[test]
  335. fn test_versioned_message_serialization() {
  336. let message = VersionedMessage::V0(v0::Message {
  337. header: MessageHeader {
  338. num_required_signatures: 1,
  339. num_readonly_signed_accounts: 0,
  340. num_readonly_unsigned_accounts: 0,
  341. },
  342. recent_blockhash: Hash::new_unique(),
  343. account_keys: vec![Pubkey::new_unique()],
  344. address_table_lookups: vec![
  345. MessageAddressTableLookup {
  346. account_key: Pubkey::new_unique(),
  347. writable_indexes: vec![1],
  348. readonly_indexes: vec![0],
  349. },
  350. MessageAddressTableLookup {
  351. account_key: Pubkey::new_unique(),
  352. writable_indexes: vec![0],
  353. readonly_indexes: vec![1],
  354. },
  355. ],
  356. instructions: vec![CompiledInstruction {
  357. program_id_index: 1,
  358. accounts: vec![0, 2, 3, 4],
  359. data: vec![],
  360. }],
  361. });
  362. let bytes = bincode::serialize(&message).unwrap();
  363. let message_from_bytes: VersionedMessage = bincode::deserialize(&bytes).unwrap();
  364. assert_eq!(message, message_from_bytes);
  365. let string = serde_json::to_string(&message).unwrap();
  366. let message_from_string: VersionedMessage = serde_json::from_str(&string).unwrap();
  367. assert_eq!(message, message_from_string);
  368. }
  369. }