1use core::fmt;
9
10use serde::{Deserialize, Serialize};
11
12use crate::sha256;
13
14pub const EFFECT_ABI_V2: &str = "0.2";
16
17#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(deny_unknown_fields)]
20pub struct EffectContractV2 {
21 #[serde(rename = "effectAbiVersion")]
23 pub effect_abi_version: String,
24 pub deployment: DeploymentBindingV2,
26 pub instructions: Vec<InstructionEffectContractV2>,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
33pub enum DeploymentBindingV2 {
34 ExactDeployment {
36 #[serde(rename = "programId")]
37 program_id: [u8; 32],
38 #[serde(rename = "loaderId")]
39 loader_id: [u8; 32],
40 #[serde(rename = "executableDigest")]
41 executable_digest: [u8; 32],
42 },
43 ExactArtifact {
46 #[serde(rename = "executableDigest")]
47 executable_digest: [u8; 32],
48 },
49}
50
51impl DeploymentBindingV2 {
52 pub fn executable_digest(&self) -> [u8; 32] {
54 match self {
55 Self::ExactDeployment {
56 executable_digest, ..
57 }
58 | Self::ExactArtifact { executable_digest } => *executable_digest,
59 }
60 }
61}
62
63#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(deny_unknown_fields)]
66pub struct InstructionEffectContractV2 {
67 pub name: String,
68 #[serde(rename = "discriminatorBytes")]
70 pub discriminator: Vec<u8>,
71 pub completeness: ContractCompletenessV2,
73 pub accounts: Vec<AccountRoleContractV2>,
75 #[serde(rename = "remainingAccounts")]
77 pub remaining_accounts: RemainingAccountsContractV2,
78 pub cpi: CpiPolicyV2,
80}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(deny_unknown_fields)]
85pub struct ContractCompletenessV2 {
86 pub accounts: bool,
87 pub data: bool,
88 pub lamports: bool,
89 pub owner: bool,
90 #[serde(rename = "dataLength")]
91 pub data_length: bool,
92 pub presence: bool,
93 pub executable: bool,
94 pub cpi: bool,
95}
96
97#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(deny_unknown_fields)]
100pub struct AccountRoleContractV2 {
101 pub name: String,
102 pub signer: PrivilegeRequirementV2,
103 pub writable: PrivilegeRequirementV2,
104 pub address: AddressConstraintV2,
105 pub transition: TransitionPolicyV2,
106}
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub enum PrivilegeRequirementV2 {
112 Required,
113 Forbidden,
114 Allowed,
115}
116
117#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
120pub enum AddressConstraintV2 {
121 Any,
122 Exact {
123 address: [u8; 32],
124 },
125 ProgramId,
127}
128
129#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
131#[serde(deny_unknown_fields)]
132pub struct TransitionPolicyV2 {
133 pub data: DataPolicyV2,
134 pub lamports: LamportPolicyV2,
135 pub owner: OwnerPolicyV2,
136 #[serde(rename = "dataLength")]
137 pub data_length: LengthPolicyV2,
138 pub presence: PresencePolicyV2,
139 pub executable: ExecutablePolicyV2,
140}
141
142#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
144#[serde(deny_unknown_fields)]
145pub struct DataPolicyV2 {
146 pub ranges: Vec<DataRangeV2>,
147}
148
149#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(deny_unknown_fields)]
152pub struct DataRangeV2 {
153 pub offset: u32,
154 pub size: u32,
155}
156
157impl DataRangeV2 {
158 pub fn end(self) -> u64 {
159 self.offset as u64 + self.size as u64
160 }
161
162 pub fn contains(self, offset: u64) -> bool {
163 self.offset as u64 <= offset && offset < self.end()
164 }
165}
166
167#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase")]
170pub enum LamportPolicyV2 {
171 Preserve,
172 MayChange,
173 DebitOnly,
174 CreditOnly,
175}
176
177#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
180pub enum OwnerPolicyV2 {
181 Preserve,
182 SetTo { target: OwnerTargetV2 },
183 MayChange,
184}
185
186#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
188#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
189pub enum OwnerTargetV2 {
190 Exact { address: [u8; 32] },
191 ProgramId,
192 SystemProgram,
193}
194
195#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
198pub enum LengthPolicyV2 {
199 Preserve,
200 Exact { length: u32 },
201 Range { min: u32, max: u32 },
202 MayChange,
203}
204
205#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase")]
209pub enum PresencePolicyV2 {
210 Preserve,
211 MustRemainPresent,
212 MustCreate,
213 MayCreate,
214 MustClose,
215 MayClose,
216}
217
218#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
221pub enum ExecutablePolicyV2 {
222 Preserve,
223 Set { value: bool },
224 MayChange,
225}
226
227#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(deny_unknown_fields)]
230pub struct RemainingAccountsContractV2 {
231 pub complete: bool,
232 #[serde(rename = "allowTrailing")]
234 pub allow_trailing: bool,
235 #[serde(rename = "duplicatePolicy")]
236 pub duplicate_policy: DuplicatePolicyV2,
237 pub groups: Vec<RemainingGroupV2>,
238}
239
240#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(deny_unknown_fields)]
243pub struct RemainingGroupV2 {
244 pub name: String,
245 pub repeat: u16,
246 pub roles: Vec<AccountRoleContractV2>,
247}
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "camelCase")]
252pub enum DuplicatePolicyV2 {
253 DenyAll,
254 DenyWritable,
255 Allow,
256}
257
258#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
260#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
261pub enum CpiPolicyV2 {
262 Forbidden,
263 Declared {
264 complete: bool,
265 calls: Vec<CpiEnvelopeV2>,
266 },
267}
268
269#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
271#[serde(deny_unknown_fields)]
272pub struct CpiEnvelopeV2 {
273 pub id: String,
274 #[serde(rename = "programId")]
275 pub program_id: [u8; 32],
276 #[serde(rename = "loaderId")]
277 pub loader_id: [u8; 32],
278 #[serde(rename = "executableDigest")]
279 pub executable_digest: [u8; 32],
280 #[serde(rename = "discriminatorBytes")]
281 pub discriminator: Vec<u8>,
282 #[serde(rename = "minCalls")]
283 pub min_calls: u16,
284 #[serde(rename = "maxCalls")]
285 pub max_calls: u16,
286 #[serde(rename = "allowRollback")]
287 pub allow_rollback: bool,
288 #[serde(rename = "allowExtraAccounts")]
289 pub allow_extra_accounts: bool,
290 pub accounts: Vec<CpiAccountBindingV2>,
291}
292
293#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
295#[serde(deny_unknown_fields)]
296pub struct CpiAccountBindingV2 {
297 #[serde(rename = "childPosition")]
298 pub child_position: u16,
299 #[serde(rename = "parentPosition")]
300 pub parent_position: u16,
301 pub signer: PrivilegeRequirementV2,
302 pub writable: PrivilegeRequirementV2,
303}
304
305#[derive(Clone, Debug, PartialEq, Eq)]
307pub enum EffectContractV2Error {
308 Json(String),
309 UnsupportedVersion(String),
310 InvalidContract(String),
311}
312
313impl fmt::Display for EffectContractV2Error {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 match self {
316 Self::Json(message) => write!(f, "effect v0.2 JSON error: {message}"),
317 Self::UnsupportedVersion(version) => {
318 write!(f, "unsupported Effect ABI version `{version}`")
319 }
320 Self::InvalidContract(message) => write!(f, "invalid Effect ABI v0.2: {message}"),
321 }
322 }
323}
324
325impl std::error::Error for EffectContractV2Error {}
326
327impl EffectContractV2 {
328 pub fn from_json(json: &str) -> Result<Self, EffectContractV2Error> {
330 let contract: Self = serde_json::from_str(json)
331 .map_err(|error| EffectContractV2Error::Json(error.to_string()))?;
332 contract.validate()?;
333 Ok(contract)
334 }
335
336 pub fn validate(&self) -> Result<(), EffectContractV2Error> {
339 if self.effect_abi_version != EFFECT_ABI_V2 {
340 return Err(EffectContractV2Error::UnsupportedVersion(
341 self.effect_abi_version.clone(),
342 ));
343 }
344 if self.instructions.is_empty() {
345 return invalid("instructions must not be empty");
346 }
347 for (index, instruction) in self.instructions.iter().enumerate() {
348 validate_instruction(instruction)?;
349 for other in &self.instructions[index + 1..] {
350 if instruction.name == other.name {
351 return invalid(format!("duplicate instruction name `{}`", instruction.name));
352 }
353 if is_prefix(&instruction.discriminator, &other.discriminator)
354 || is_prefix(&other.discriminator, &instruction.discriminator)
355 {
356 return invalid(format!(
357 "instruction discriminators for `{}` and `{}` are equal or prefix-shadowed",
358 instruction.name, other.name
359 ));
360 }
361 }
362 }
363 Ok(())
364 }
365
366 pub fn instruction_for_data(&self, data: &[u8]) -> Option<&InstructionEffectContractV2> {
368 self.instructions
369 .iter()
370 .find(|instruction| data.starts_with(&instruction.discriminator))
371 }
372
373 pub fn canonical_bytes(&self) -> Result<Vec<u8>, EffectContractV2Error> {
375 self.validate()?;
376 let mut out = Vec::new();
377 out.extend_from_slice(b"grillo.effect-contract.v0.2.c1");
378 encode_string(&mut out, &self.effect_abi_version);
379 encode_deployment(&mut out, &self.deployment);
380 encode_len(&mut out, self.instructions.len());
381 for instruction in &self.instructions {
382 encode_instruction(&mut out, instruction);
383 }
384 Ok(out)
385 }
386
387 pub fn commitment(&self) -> Result<[u8; 32], EffectContractV2Error> {
389 Ok(sha256(&self.canonical_bytes()?))
390 }
391}
392
393impl InstructionEffectContractV2 {
394 pub fn expanded_roles(&self) -> Vec<(String, AccountRoleContractV2)> {
396 let mut out = Vec::new();
397 for role in &self.accounts {
398 out.push((role.name.clone(), role.clone()));
399 }
400 for group in &self.remaining_accounts.groups {
401 for iteration in 0..group.repeat {
402 for role in &group.roles {
403 out.push((
404 format!("{}.{}[{}]", group.name, role.name, iteration),
405 role.clone(),
406 ));
407 }
408 }
409 }
410 out
411 }
412}
413
414fn validate_instruction(
415 instruction: &InstructionEffectContractV2,
416) -> Result<(), EffectContractV2Error> {
417 if instruction.name.is_empty() {
418 return invalid("instruction name must not be empty");
419 }
420 if instruction.discriminator.is_empty() || instruction.discriminator.len() > 32 {
421 return invalid(format!(
422 "instruction `{}` discriminator length must be 1..=32",
423 instruction.name
424 ));
425 }
426 if instruction.completeness.accounts
427 && (!instruction.remaining_accounts.complete
428 || instruction.remaining_accounts.allow_trailing)
429 {
430 return invalid(format!(
431 "instruction `{}` claims complete accounts but its remaining grammar is open",
432 instruction.name
433 ));
434 }
435 if instruction.completeness.cpi {
436 if let CpiPolicyV2::Declared { complete, .. } = &instruction.cpi {
437 if !complete {
438 return invalid(format!(
439 "instruction `{}` claims complete CPI but its declaration is incomplete",
440 instruction.name
441 ));
442 }
443 }
444 }
445
446 let mut total = instruction.accounts.len();
447 validate_role_names(
448 &instruction.accounts,
449 &format!("instruction `{}`", instruction.name),
450 )?;
451 for role in &instruction.accounts {
452 validate_role(role)?;
453 }
454 for (group_index, group) in instruction.remaining_accounts.groups.iter().enumerate() {
455 if group.name.is_empty() {
456 return invalid("remaining group name must not be empty");
457 }
458 for other in &instruction.remaining_accounts.groups[group_index + 1..] {
459 if group.name == other.name {
460 return invalid(format!("duplicate remaining group `{}`", group.name));
461 }
462 }
463 if group.repeat > 0 && group.roles.is_empty() {
464 return invalid(format!(
465 "remaining group `{}` repeats but has no roles",
466 group.name
467 ));
468 }
469 validate_role_names(&group.roles, &format!("remaining group `{}`", group.name))?;
470 for role in &group.roles {
471 validate_role(role)?;
472 }
473 total = total
474 .checked_add(group.roles.len().saturating_mul(group.repeat as usize))
475 .ok_or_else(|| {
476 EffectContractV2Error::InvalidContract("account expansion overflows".into())
477 })?;
478 }
479 if total > 256 {
480 return invalid(format!(
481 "instruction `{}` expands to {total} accounts; maximum is 256",
482 instruction.name
483 ));
484 }
485 validate_cpi(&instruction.cpi, total, &instruction.name)
486}
487
488fn validate_role_names(
489 roles: &[AccountRoleContractV2],
490 scope: &str,
491) -> Result<(), EffectContractV2Error> {
492 for (index, role) in roles.iter().enumerate() {
493 if role.name.is_empty() {
494 return invalid(format!("{scope} contains an empty role name"));
495 }
496 if roles[index + 1..]
497 .iter()
498 .any(|other| other.name == role.name)
499 {
500 return invalid(format!("{scope} contains duplicate role `{}`", role.name));
501 }
502 }
503 Ok(())
504}
505
506fn validate_role(role: &AccountRoleContractV2) -> Result<(), EffectContractV2Error> {
507 for range in &role.transition.data.ranges {
508 if range.size == 0 || range.end() > u32::MAX as u64 {
509 return invalid(format!(
510 "role `{}` has an empty or overflowing data range",
511 role.name
512 ));
513 }
514 }
515 if let LengthPolicyV2::Range { min, max } = role.transition.data_length {
516 if min > max {
517 return invalid(format!("role `{}` length range is inverted", role.name));
518 }
519 }
520 Ok(())
521}
522
523fn validate_cpi(
524 policy: &CpiPolicyV2,
525 parent_account_count: usize,
526 instruction_name: &str,
527) -> Result<(), EffectContractV2Error> {
528 let CpiPolicyV2::Declared { complete, calls } = policy else {
529 return Ok(());
530 };
531 if *complete && calls.iter().any(|call| call.allow_extra_accounts) {
532 return invalid(format!(
533 "instruction `{instruction_name}` has a complete CPI policy with an open child account envelope"
534 ));
535 }
536 for (index, call) in calls.iter().enumerate() {
537 if call.id.is_empty() || call.discriminator.is_empty() || call.discriminator.len() > 32 {
538 return invalid(format!(
539 "instruction `{instruction_name}` has a CPI call with an empty id or invalid discriminator"
540 ));
541 }
542 if call.min_calls > call.max_calls || call.max_calls == 0 {
543 return invalid(format!(
544 "CPI envelope `{}` has invalid call bounds",
545 call.id
546 ));
547 }
548 for other in &calls[index + 1..] {
549 if call.id == other.id {
550 return invalid(format!("duplicate CPI envelope id `{}`", call.id));
551 }
552 if call.program_id == other.program_id
553 && (is_prefix(&call.discriminator, &other.discriminator)
554 || is_prefix(&other.discriminator, &call.discriminator))
555 {
556 return invalid(format!(
557 "CPI envelopes `{}` and `{}` are discriminator-ambiguous",
558 call.id, other.id
559 ));
560 }
561 }
562 for (binding_index, binding) in call.accounts.iter().enumerate() {
563 if binding.parent_position as usize >= parent_account_count {
564 return invalid(format!(
565 "CPI envelope `{}` references parent position {} outside {parent_account_count}",
566 call.id, binding.parent_position
567 ));
568 }
569 if call.accounts[binding_index + 1..]
570 .iter()
571 .any(|other| other.child_position == binding.child_position)
572 {
573 return invalid(format!(
574 "CPI envelope `{}` binds child position {} twice",
575 call.id, binding.child_position
576 ));
577 }
578 }
579 if !call.allow_extra_accounts {
580 for expected in 0..call.accounts.len() {
581 if !call
582 .accounts
583 .iter()
584 .any(|binding| binding.child_position as usize == expected)
585 {
586 return invalid(format!(
587 "CPI envelope `{}` has a gap at child position {expected}",
588 call.id
589 ));
590 }
591 }
592 }
593 }
594 Ok(())
595}
596
597fn invalid<T>(message: impl Into<String>) -> Result<T, EffectContractV2Error> {
598 Err(EffectContractV2Error::InvalidContract(message.into()))
599}
600
601fn is_prefix(left: &[u8], right: &[u8]) -> bool {
602 right.starts_with(left)
603}
604
605fn encode_instruction(out: &mut Vec<u8>, instruction: &InstructionEffectContractV2) {
606 encode_string(out, &instruction.name);
607 encode_bytes(out, &instruction.discriminator);
608 encode_completeness(out, instruction.completeness);
609 encode_len(out, instruction.accounts.len());
610 for role in &instruction.accounts {
611 encode_role(out, role);
612 }
613 out.push(instruction.remaining_accounts.complete as u8);
614 out.push(instruction.remaining_accounts.allow_trailing as u8);
615 out.push(duplicate_tag(
616 instruction.remaining_accounts.duplicate_policy,
617 ));
618 encode_len(out, instruction.remaining_accounts.groups.len());
619 for group in &instruction.remaining_accounts.groups {
620 encode_string(out, &group.name);
621 out.extend_from_slice(&group.repeat.to_le_bytes());
622 encode_len(out, group.roles.len());
623 for role in &group.roles {
624 encode_role(out, role);
625 }
626 }
627 encode_cpi(out, &instruction.cpi);
628}
629
630fn encode_deployment(out: &mut Vec<u8>, deployment: &DeploymentBindingV2) {
631 match deployment {
632 DeploymentBindingV2::ExactDeployment {
633 program_id,
634 loader_id,
635 executable_digest,
636 } => {
637 out.push(0);
638 out.extend_from_slice(program_id);
639 out.extend_from_slice(loader_id);
640 out.extend_from_slice(executable_digest);
641 }
642 DeploymentBindingV2::ExactArtifact { executable_digest } => {
643 out.push(1);
644 out.extend_from_slice(executable_digest);
645 }
646 }
647}
648
649fn encode_completeness(out: &mut Vec<u8>, c: ContractCompletenessV2) {
650 out.extend_from_slice(&[
651 c.accounts as u8,
652 c.data as u8,
653 c.lamports as u8,
654 c.owner as u8,
655 c.data_length as u8,
656 c.presence as u8,
657 c.executable as u8,
658 c.cpi as u8,
659 ]);
660}
661
662fn encode_role(out: &mut Vec<u8>, role: &AccountRoleContractV2) {
663 encode_string(out, &role.name);
664 out.push(privilege_tag(role.signer));
665 out.push(privilege_tag(role.writable));
666 match &role.address {
667 AddressConstraintV2::Any => out.push(0),
668 AddressConstraintV2::Exact { address } => {
669 out.push(1);
670 out.extend_from_slice(address);
671 }
672 AddressConstraintV2::ProgramId => out.push(2),
673 }
674 encode_len(out, role.transition.data.ranges.len());
675 for range in &role.transition.data.ranges {
676 out.extend_from_slice(&range.offset.to_le_bytes());
677 out.extend_from_slice(&range.size.to_le_bytes());
678 }
679 out.push(lamport_tag(role.transition.lamports));
680 encode_owner(out, &role.transition.owner);
681 encode_length(out, &role.transition.data_length);
682 out.push(presence_tag(role.transition.presence));
683 match role.transition.executable {
684 ExecutablePolicyV2::Preserve => out.push(0),
685 ExecutablePolicyV2::Set { value } => out.extend_from_slice(&[1, value as u8]),
686 ExecutablePolicyV2::MayChange => out.push(2),
687 }
688}
689
690fn encode_owner(out: &mut Vec<u8>, policy: &OwnerPolicyV2) {
691 match policy {
692 OwnerPolicyV2::Preserve => out.push(0),
693 OwnerPolicyV2::SetTo { target } => {
694 out.push(1);
695 match target {
696 OwnerTargetV2::Exact { address } => {
697 out.push(0);
698 out.extend_from_slice(address);
699 }
700 OwnerTargetV2::ProgramId => out.push(1),
701 OwnerTargetV2::SystemProgram => out.push(2),
702 }
703 }
704 OwnerPolicyV2::MayChange => out.push(2),
705 }
706}
707
708fn encode_length(out: &mut Vec<u8>, policy: &LengthPolicyV2) {
709 match policy {
710 LengthPolicyV2::Preserve => out.push(0),
711 LengthPolicyV2::Exact { length } => {
712 out.push(1);
713 out.extend_from_slice(&length.to_le_bytes());
714 }
715 LengthPolicyV2::Range { min, max } => {
716 out.push(2);
717 out.extend_from_slice(&min.to_le_bytes());
718 out.extend_from_slice(&max.to_le_bytes());
719 }
720 LengthPolicyV2::MayChange => out.push(3),
721 }
722}
723
724fn encode_cpi(out: &mut Vec<u8>, policy: &CpiPolicyV2) {
725 match policy {
726 CpiPolicyV2::Forbidden => out.push(0),
727 CpiPolicyV2::Declared { complete, calls } => {
728 out.extend_from_slice(&[1, *complete as u8]);
729 encode_len(out, calls.len());
730 for call in calls {
731 encode_string(out, &call.id);
732 out.extend_from_slice(&call.program_id);
733 out.extend_from_slice(&call.loader_id);
734 out.extend_from_slice(&call.executable_digest);
735 encode_bytes(out, &call.discriminator);
736 out.extend_from_slice(&call.min_calls.to_le_bytes());
737 out.extend_from_slice(&call.max_calls.to_le_bytes());
738 out.push(call.allow_rollback as u8);
739 out.push(call.allow_extra_accounts as u8);
740 encode_len(out, call.accounts.len());
741 for binding in &call.accounts {
742 out.extend_from_slice(&binding.child_position.to_le_bytes());
743 out.extend_from_slice(&binding.parent_position.to_le_bytes());
744 out.push(privilege_tag(binding.signer));
745 out.push(privilege_tag(binding.writable));
746 }
747 }
748 }
749 }
750}
751
752fn encode_string(out: &mut Vec<u8>, value: &str) {
753 encode_bytes(out, value.as_bytes());
754}
755
756fn encode_bytes(out: &mut Vec<u8>, value: &[u8]) {
757 encode_len(out, value.len());
758 out.extend_from_slice(value);
759}
760
761fn encode_len(out: &mut Vec<u8>, value: usize) {
762 out.extend_from_slice(&(value as u32).to_le_bytes());
763}
764
765fn privilege_tag(value: PrivilegeRequirementV2) -> u8 {
766 match value {
767 PrivilegeRequirementV2::Required => 0,
768 PrivilegeRequirementV2::Forbidden => 1,
769 PrivilegeRequirementV2::Allowed => 2,
770 }
771}
772
773fn duplicate_tag(value: DuplicatePolicyV2) -> u8 {
774 match value {
775 DuplicatePolicyV2::DenyAll => 0,
776 DuplicatePolicyV2::DenyWritable => 1,
777 DuplicatePolicyV2::Allow => 2,
778 }
779}
780
781fn lamport_tag(value: LamportPolicyV2) -> u8 {
782 match value {
783 LamportPolicyV2::Preserve => 0,
784 LamportPolicyV2::MayChange => 1,
785 LamportPolicyV2::DebitOnly => 2,
786 LamportPolicyV2::CreditOnly => 3,
787 }
788}
789
790fn presence_tag(value: PresencePolicyV2) -> u8 {
791 match value {
792 PresencePolicyV2::Preserve => 0,
793 PresencePolicyV2::MustRemainPresent => 1,
794 PresencePolicyV2::MustCreate => 2,
795 PresencePolicyV2::MayCreate => 3,
796 PresencePolicyV2::MustClose => 4,
797 PresencePolicyV2::MayClose => 5,
798 }
799}
800
801#[cfg(test)]
802mod tests {
803 use super::*;
804
805 fn preserve() -> TransitionPolicyV2 {
806 TransitionPolicyV2 {
807 data: DataPolicyV2 { ranges: vec![] },
808 lamports: LamportPolicyV2::Preserve,
809 owner: OwnerPolicyV2::Preserve,
810 data_length: LengthPolicyV2::Preserve,
811 presence: PresencePolicyV2::Preserve,
812 executable: ExecutablePolicyV2::Preserve,
813 }
814 }
815
816 fn contract() -> EffectContractV2 {
817 EffectContractV2 {
818 effect_abi_version: EFFECT_ABI_V2.into(),
819 deployment: DeploymentBindingV2::ExactArtifact {
820 executable_digest: [7; 32],
821 },
822 instructions: vec![InstructionEffectContractV2 {
823 name: "set".into(),
824 discriminator: vec![1, 2],
825 completeness: ContractCompletenessV2 {
826 accounts: true,
827 data: true,
828 lamports: true,
829 owner: true,
830 data_length: true,
831 presence: true,
832 executable: true,
833 cpi: true,
834 },
835 accounts: vec![AccountRoleContractV2 {
836 name: "state".into(),
837 signer: PrivilegeRequirementV2::Forbidden,
838 writable: PrivilegeRequirementV2::Required,
839 address: AddressConstraintV2::Any,
840 transition: preserve(),
841 }],
842 remaining_accounts: RemainingAccountsContractV2 {
843 complete: true,
844 allow_trailing: false,
845 duplicate_policy: DuplicatePolicyV2::DenyWritable,
846 groups: vec![],
847 },
848 cpi: CpiPolicyV2::Forbidden,
849 }],
850 }
851 }
852
853 #[test]
854 fn commitment_covers_full_discriminator_and_roles() {
855 let base = contract().commitment().unwrap();
856 let mut changed = contract();
857 changed.instructions[0].discriminator[1] = 3;
858 assert_ne!(base, changed.commitment().unwrap());
859 let mut changed = contract();
860 changed.instructions[0].accounts[0].writable = PrivilegeRequirementV2::Allowed;
861 assert_ne!(base, changed.commitment().unwrap());
862 }
863
864 #[test]
865 fn discriminator_prefix_shadow_is_rejected() {
866 let mut value = contract();
867 let mut second = value.instructions[0].clone();
868 second.name = "shadow".into();
869 second.discriminator = vec![1, 2, 3];
870 value.instructions.push(second);
871 assert!(matches!(
872 value.validate(),
873 Err(EffectContractV2Error::InvalidContract(message)) if message.contains("prefix-shadowed")
874 ));
875 }
876}