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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
#![doc = include_str!("../README.md")]
#![recursion_limit = "128"]
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
extern crate syn;
use proc_macro::TokenStream;
use syn::{parse_macro_input, parse_quote, AttributeArgs};
use pbc_contract_codegen_internal::{
action_macro, callback_macro, init_macro, parse_attributes,
parse_secret_input_type_from_attributes, parse_secret_input_type_from_function_return,
parse_shortname_override, parse_zk_argument, state_macro, zk_macro, SecretInput,
WrappedFunctionKind,
};
use pbc_contract_common::FunctionKind;
/// State contract annotation
///
/// **REQUIRED ANNOTATION**: This is a required annotation. A contract cannot be created without
/// a state.
///
/// Declares that the annotated struct is the top level of the contract state. This
/// macro must occur exactly once in any given contract.
///
/// # Example
///
/// ```ignore
/// # use pbc_contract_common::address::Address;
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::sorted_vec_map::SortedVecMap;
/// #[state]
/// pub struct VotingContractState {
/// proposal_id: u64,
/// mp_addresses: Vec<Address>,
/// votes: SortedVecMap<Address, u8>,
/// closed: u8,
/// }
/// ```
///
/// This macro implicitly derives [`ReadWriteState`](pbc_traits::ReadWriteState) for the struct.
/// The [`ReadWriteState`](pbc_traits::ReadWriteState) derive may fail if any of the state struct's
/// fields aren't impl [`ReadWriteState`](pbc_traits::ReadWriteState).
///
/// Furthermore, note that state serialization speeds are heavily affected by the types contained
/// in the state struct. Types with dynamic sizes ([`Option<T>`], [`String`])
/// are especially slow. For more background, see
/// [`ReadWriteState::SERIALIZABLE_BY_COPY`](pbc_traits::ReadWriteState::SERIALIZABLE_BY_COPY)
#[proc_macro_attribute]
pub fn state(_attrs: TokenStream, input: TokenStream) -> TokenStream {
state_macro::handle_state_macro(input)
}
/// Initializer contract annotation
///
/// **REQUIRED HOOK**: This is a required hook. A contract cannot be created without an
/// initializer.
///
/// Init declares how the contract can be initialized. Init is an [`macro@action`] that is forced to run to initialize
/// the contract. Must occur exactly once in any given contract.
///
/// If the annotated function panics the contract will not be created.
///
/// Annotated function must have a signature of following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
/// #[init]
/// pub fn initialize(
/// context: ContractContext,
/// // ... Invocation RPC arguments
/// ) -> (ContractState, Vec<EventGroup>)
/// # { (0, vec![]) }
/// ```
///
/// with following constraints:
///
/// - `ContractState` must be the type annotated with [`macro@state`], and must have an
/// [`pbc_traits::ReadWriteState`] implementation.
/// - Additional arguments are must have [`pbc_traits::ReadRPC`] and [`pbc_traits::WriteRPC`]
/// implementations. These are treated as invocation arguments, and are included in the ABI.
///
/// Note that there are no previous state when initializing, in contrast to the
/// [`macro@action`] macro. If the initializer fails the contract will not be created.
#[proc_macro_attribute]
pub fn init(attrs: TokenStream, input: TokenStream) -> TokenStream {
let args: AttributeArgs = parse_macro_input!(attrs as AttributeArgs);
let attributes = parse_attributes(args, vec!["zk".to_string()], vec![]);
let zk = parse_zk_argument(&attributes);
init_macro::handle_init_macro(input, zk)
}
/// Public `action` contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook. Most contracts will need at least one `action` hook.
///
/// Annotated function is a contract `action` that can be called from other contracts and dashboard.
///
/// If the annotated function panics the contract state [will be rolled back to the state before the action](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Must have a signature of the following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
/// # #[init(zk = false)] pub fn initialize(context: ContractContext) -> ContractState { 0 }
/// #[action(shortname = 0x33)]
/// pub fn action_internal_name(
/// context: ContractContext,
/// state: ContractState,
/// // ... Invocation RPC arguments
/// ) -> (ContractState, Vec<EventGroup>)
/// # { (0, vec![]) }
/// ```
///
/// with the following constraints:
///
/// - `ContractState` must be the type annotated with [`macro@state`], and must have an
/// [`pbc_traits::ReadWriteState`] implementation.
/// - Additional arguments are must have [`pbc_traits::ReadRPC`] and [`pbc_traits::WriteRPC`]
/// implementations. These are treated as invocation arguments, and are included in the ABI.
///
/// The invocation receives the previous state, along with a context, and the declared
/// arguments, and must return the new state, along with a vector of
/// [`pbc_contract_common::events::EventGroup`]; a list of interactions with other contracts.
///
/// # Example
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::events::*;
/// # use pbc_contract_common::address::*;
/// # use pbc_contract_common::sorted_vec_map::SortedVecMap;
/// type ContractState = SortedVecMap<Address, bool>;
/// # type Metadata = u32;
///
/// # #[init(zk = false)] pub fn initialize(context: ContractContext) -> ContractState { SortedVecMap::new() }
/// #[action(shortname = 0x11)]
/// pub fn vote(
/// context: ContractContext,
/// mut state: ContractState,
/// vote: bool,
/// ) -> ContractState {
/// state.insert(context.sender, vote);
/// state
/// }
/// ```
///
/// # Shortname
///
/// In addition to the readable name, every invocation needs a shortname, a small unique identifier.
/// This shortname is automatically generated by default, but for cases where a specific shortname
/// is desirable, it can be set using the `shortname = <shortname>` attribute.
/// This has to be a [`u32`] and gets encoded as LEB128 (up to 5 bytes). These bytes are then
/// encoded as lowercase zero-padded hex.
///
/// For example:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// type Metadata = u32;
///
/// # #[init(zk = false)] pub fn initialize(context: ContractContext) -> ContractState { 0 }
/// #[action(shortname = 0x53)]
/// pub fn some_action(
/// context: ContractContext,
/// mut state: ContractState,
/// ) -> (ContractState, Vec<EventGroup>) {
/// // Do things
/// (state, vec![])
/// }
/// ```
#[proc_macro_attribute]
pub fn action(attrs: TokenStream, input: TokenStream) -> TokenStream {
let args: AttributeArgs = parse_macro_input!(attrs as AttributeArgs);
let attributes = parse_attributes(
args,
vec!["shortname".to_string(), "zk".to_string()],
vec![],
);
let shortname_override = parse_shortname_override(&attributes);
let zk = parse_zk_argument(&attributes);
action_macro::handle_action_macro(input, shortname_override, zk)
}
/// Public callback contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook, only required if the contract needs callback
/// functionality.
///
/// Annotated function is a callback from an event sent by this contract. Unlike actions,
/// callbacks must specify their shortname explicitly.
///
/// If the annotated function panics the contract state [will be rolled back to the state before the callback](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Must have a signature of the following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
/// # #[init(zk = false)] pub fn initialize(context: ContractContext) -> ContractState { 0 }
/// #[callback(shortname = 0x13)]
/// pub fn callback_internal_name(
/// contract_context: ContractContext,
/// callback_context: CallbackContext,
/// state: ContractState,
/// // ... Invocation RPC arguments
/// ) -> (ContractState, Vec<EventGroup>)
/// # { (0, vec![]) }
/// ```
///
/// with following constraints:
///
/// - `ContractState` must be the type annotated with [`macro@state`], and must have an
/// [`pbc_traits::ReadWriteState`] implementation.
/// - Additional arguments are must have [`pbc_traits::ReadRPC`] and [`pbc_traits::WriteRPC`]
/// implementations. These are treated as invocation arguments, and are included in the ABI.
///
/// The callback receives the previous state, along with two context objects, and the declared
/// arguments. The [`CallbackContext`](pbc_contract_common::context::CallbackContext) object contains the execution status of all the events
/// sent by the original transaction.
/// Just like actions, callbacks must return the new state, along with a vector of
/// [`EventGroup`](pbc_contract_common::events::EventGroup); a list of interactions with other contracts.
///
/// # Shortname
///
/// In addition to the readable name the callback needs a shortname, a small unique identifier.
/// This shortname must be set using the `shortname = <shortname>` attribute.
/// This has to be a [`u32`] and gets encoded as LEB128 (up to 5 bytes). These bytes are then
/// encoded as lowercase zero-padded hex.
#[proc_macro_attribute]
pub fn callback(attrs: TokenStream, input: TokenStream) -> TokenStream {
let args: AttributeArgs = parse_macro_input!(attrs as AttributeArgs);
let attributes = parse_attributes(
args,
vec!["shortname".to_string(), "zk".to_string()],
vec!["shortname".to_string()],
);
let shortname_override = parse_shortname_override(&attributes);
let zk = parse_zk_argument(&attributes);
callback_macro::handle_callback_macro(input, shortname_override, zk)
}
/// Secret input/action contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook. Most zero-knowledge contracts will need at least
/// one.
///
/// Annotated function is a contract invocation that allows a user to deliver secret input to the
/// contract. Can be thought of as the Zk variant of [`macro@action`]. The notable change is the
/// introduction of a required return value, of type
/// [`ZkInputDef`](pbc_contract_common::zk::ZkInputDef), that contains contract-supplied metadata,
/// along with some other configuration for the secret variable.
///
/// If the annotated function panics the input will be rejected, and changes to the contract state [will be rolled back](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Must have a signature of the following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// use pbc_zk_core::Sbi32;
/// # type ContractState = u32;
/// # type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_secret_input(shortname = 0xDEADB00F)]
/// pub fn function_name(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// // ... Invocation RPC arguments.
/// ) -> (ContractState, Vec<EventGroup>, ZkInputDef<Metadata, Sbi32>) {
/// (state, vec![], ZkInputDef::with_metadata(Some(SHORTNAME_MY_ON_INPUTTED), 0))
/// }
///
/// #[zk_on_variable_inputted(shortname=0x13)]
/// pub fn my_on_inputted(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// variable_id: SecretVarId,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
/// // ...
/// # (state, vec![], vec![])
/// }
/// ```
///
/// with following constraints:
///
/// - `ContractState` must be the type annotated with [`macro@state`], and must have an
/// [`pbc_traits::ReadWriteState`] implementation.
/// - Invocation arguments must have a [`pbc_traits::ReadRPC`]
/// and a [`pbc_traits::WriteRPC`] implementation.
/// - The `Metadata` type given to [`ZkState`](pbc_contract_common::zk::ZkState) and [`ZkInputDef`](pbc_contract_common::zk::ZkInputDef) must be identical both for individual
/// functions, and across the entire contract.
/// - This function is only available with the `zk` feature enabled.
///
/// The function receives the previous states `ContractState` and
/// [`ZkState<Metadata>`](pbc_contract_common::zk::ZkState), along with the
/// [`ContractContext`](pbc_contract_common::context::ContractContext), and the declared RPC
/// arguments.
///
/// The function must return a tuple containing:
///
/// - New public state.
/// - Vector of [`EventGroup`](pbc_contract_common::events::EventGroup); a list of interactions with other contracts.
/// - Instance of [`ZkInputDef<Metadata>`](pbc_contract_common::zk::ZkInputDef) for declaring the
/// layout and metadata of a secret variable.
///
/// # Example
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// use pbc_zk_core::Sbi32;
/// type ContractState = u32;
/// type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_secret_input(shortname = 0x13, secret_type = "Sbi32")]
/// pub fn receive_bitlengths_10_10(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<u32>,
/// ) -> (ContractState, Vec<EventGroup>, ZkInputDef<u32, Sbi32>) {
/// let def = ZkInputDef::with_metadata(Some(SHORTNAME_MY_ON_INPUTTED), 23u32);
/// (state, vec![], def)
/// }
///
/// #[zk_on_variable_inputted(shortname=0x13)]
/// pub fn my_on_inputted(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// variable_id: SecretVarId,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
/// // ...
/// # (state, vec![], vec![])
/// }
/// ```
#[proc_macro_attribute]
pub fn zk_on_secret_input(attrs: TokenStream, input: TokenStream) -> TokenStream {
let fn_ast: syn::ItemFn = syn::parse(input.clone()).unwrap();
let secret_type_input = parse_secret_input_type_from_function_return(&fn_ast.sig.output);
let args: AttributeArgs = parse_macro_input!(attrs as AttributeArgs);
let attributes = parse_attributes(
args,
vec!["shortname".to_string(), "secret_type".to_string()],
vec!["shortname".to_string()],
);
let shortname_override = parse_shortname_override(&attributes);
// Parse secret type from attribute to validate equality, but otherwise ignore.
let secret_type_input_attribute = parse_secret_input_type_from_attributes(attributes);
if let (SecretInput::Some(t1), SecretInput::Some(t2)) =
(&secret_type_input, secret_type_input_attribute)
{
if *t1 != t2 {
panic!("Type of secret variable in function return type doesn't match type in function attribute.");
}
}
let zk_input_def_arg = quote! { pbc_contract_common::zk::ZkInputDef<_, _> };
let function_kind = WrappedFunctionKind {
output_state_and_events: true,
min_allowed_num_results: 3,
output_other_types: vec![(zk_input_def_arg, format_ident!("write_zk_input_def_result"))],
system_arguments: 3,
fn_kind: FunctionKind::ZkSecretInputWithExplicitType,
allow_rpc_arguments: true,
};
zk_macro::handle_zk_macro(
input,
shortname_override,
None,
"zk_on_secret_input",
&function_kind,
true,
secret_type_input,
)
}
/// Secret variable input zero-knowledge contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook, and is not required for a well-formed
/// zero-knowledge contract. The default behaviour is to do nothing.
///
/// If the annotated function panics changes to the contract state [will be rolled back](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Annotated function is automatically called when a Zk variable is confirmed and fully inputted.
/// This hook is exclusively called by the blockchain itself, and cannot be called manually from
/// the dashboard, nor from another contract.
///
/// Allows the contract to automatically react to ZK inputs.
///
/// Must have a signature of the following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_variable_inputted(shortname = 0x13)]
/// pub fn zk_on_variable_inputted(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// variable_id: SecretVarId,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>)
/// # { (state, vec![], vec![]) }
/// ```
///
/// with following constraints:
///
/// - `ContractState` must be the type annotated with [`macro@state`], and must have an
/// [`pbc_traits::ReadWriteState`] implementation.
/// - The `Metadata` type given to [`ZkState`](pbc_contract_common::zk::ZkState) and [`ZkInputDef`](pbc_contract_common::zk::ZkInputDef) must be identical both for individual
/// functions, and across the entire contract.
/// - This function is only available with the `zk` feature enabled.
///
/// The function receives:
/// - `ContractState`: The previous states.
/// - [`ZkState<Metadata>`](pbc_contract_common::zk::ZkState): The current state of the zk computation.
/// - [`ContractContext`](pbc_contract_common::context::ContractContext): The current contract context.
/// - [`SecretVarId`](pbc_contract_common::zk::SecretVarId): Id of the variable.
///
/// The function must return a tuple containing:
///
/// - New public state.
/// - Vector of [`EventGroup`](pbc_contract_common::events::EventGroup); a list of interactions with other contracts.
/// - [`Vec<ZkStateChange>`](pbc_contract_common::zk::ZkStateChange) declaring how to change the zk contract state.
///
/// # Example
///
/// This hook is commonly used to start the computation when enough inputs have been given, as
/// demonstrated in the following example:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// # use pbc_contract_common::shortname::ShortnameZkComputation;
/// type ContractState = u32;
/// type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// const SHORTNAME_MY_COMPUTATION : ShortnameZkComputation = ShortnameZkComputation::from_u32(0x11);
///
/// #[zk_on_variable_inputted(shortname=0x13)]
/// pub fn zk_on_variable_inputted(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// variable_id: SecretVarId,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
/// let zk_state_changes = if (zk_state.secret_variables.len() > 5) {
/// vec![ZkStateChange::start_computation(SHORTNAME_MY_COMPUTATION, vec![1, 2, 3], Some(SHORTNAME_MY_ON_COMPUTE_COMPLETE))]
/// } else {
/// vec![]
/// };
/// (state, vec![], zk_state_changes)
/// }
///
/// #[zk_on_compute_complete(shortname = 0x13)]
/// pub fn my_on_compute_complete(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// created_variables: Vec<SecretVarId>,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
/// // ...
/// # { (state, vec![], vec![]) }
/// }
/// ```
#[proc_macro_attribute]
pub fn zk_on_variable_inputted(attrs: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(attrs as AttributeArgs);
let attributes = parse_attributes(
args,
vec!["shortname".to_string()],
vec!["shortname".to_string()],
);
let shortname_override = parse_shortname_override(&attributes);
let function_kind = WrappedFunctionKind {
output_state_and_events: true,
min_allowed_num_results: 1,
output_other_types: vec![(
quote! { Vec<pbc_contract_common::zk::ZkStateChange> },
format_ident!("write_zk_state_change"),
)],
system_arguments: 4,
fn_kind: FunctionKind::ZkVarInputted,
allow_rpc_arguments: false,
};
zk_macro::handle_zk_macro(
input,
shortname_override,
Some(parse_quote! { pbc_contract_common::address::ShortnameZkVariableInputted }),
"zk_on_variable_inputted",
&function_kind,
true,
SecretInput::None,
)
}
/// Secret variable rejection zero-knowledge contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook, and is not required for a well-formed
/// zero-knowledge contract. The default behaviour is to do nothing.
///
/// If the annotated function panics changes to the contract state [will be rolled back](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Annotated function is automatically called when a Zk variable is rejected for any reason.
/// This hook is exclusively called by the blockchain itself, and cannot be called manually from
/// the dashboard, nor from another contract.
///
/// Allows the contract to automatically react to ZK input rejection.
///
/// Must have a signature of the following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_variable_rejected]
/// pub fn zk_on_variable_rejected(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// variable_id: SecretVarId,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>)
/// # { (state, vec![], vec![]) }
/// ```
#[proc_macro_attribute]
pub fn zk_on_variable_rejected(attrs: TokenStream, input: TokenStream) -> TokenStream {
assert!(
attrs.is_empty(),
"No attributes are supported for zk_on_variable_rejected"
);
let function_kind = WrappedFunctionKind {
output_state_and_events: true,
min_allowed_num_results: 1,
output_other_types: vec![(
quote! { Vec<pbc_contract_common::zk::ZkStateChange> },
format_ident!("write_zk_state_change"),
)],
system_arguments: 4,
fn_kind: FunctionKind::ZkVarRejected,
allow_rpc_arguments: false,
};
zk_macro::handle_zk_macro(
input,
None,
None,
"zk_on_variable_rejected",
&function_kind,
false,
SecretInput::None,
)
}
/// Computation complete zero-knowledge contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook, and is not required for a well-formed
/// zero-knowledge contract. The default behaviour is to do nothing.
///
/// If the annotated function panics changes to the contract state [will be rolled back](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Annotated function is automatically called when a zero-knowledge computation is finished; this
/// can only happen after the use of
/// [`ZkStateChange::StartComputation`](pbc_contract_common::zk::ZkStateChange::StartComputation).
/// This hook is exclusively called by the blockchain itself, and cannot be called manually from
/// the dashboard, nor from another contract.
///
/// Allows the contract to automatically react to ZK computation completion.
///
/// Must have a signature of the following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_compute_complete(shortname = 0x13)]
/// pub fn function_name(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// created_variables: Vec<SecretVarId>,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>)
/// # { (state, vec![], vec![]) }
/// ```
///
/// with following constraints:
///
/// - `ContractState` must be the type annotated with [`macro@state`], and must have an
/// [`pbc_traits::ReadWriteState`] implementation.
/// - The `Metadata` type given to [`ZkState`](pbc_contract_common::zk::ZkState) and [`ZkInputDef`](pbc_contract_common::zk::ZkInputDef) must be identical both for individual
/// functions, and across the entire contract.
/// - This function is only available with the `zk` feature enabled.
///
/// The function receives:
/// - `ContractState`: The previous states.
/// - [`ZkState<Metadata>`](pbc_contract_common::zk::ZkState): The current state of the zk computation.
/// - [`ContractContext`](pbc_contract_common::context::ContractContext): The current contract context.
/// - [`Vec<SecretVarId>`](pbc_contract_common::zk::SecretVarId): Ids of the computation's output variables.
///
/// The function must return a tuple containing:
///
/// - New public state.
/// - Vector of [`EventGroup`](pbc_contract_common::events::EventGroup); a list of interactions with other contracts.
/// - [`Vec<ZkStateChange>`](pbc_contract_common::zk::ZkStateChange) declaring how to change the zk contract state.
///
/// # Example
///
/// A commonly used pattern is to open the output variables given to `zk_on_compute_complete`, as
/// demonstrated in the following example:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// type ContractState = u32;
/// type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_compute_complete(shortname=0x13)]
/// pub fn zk_on_compute_complete(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// created_variables: Vec<SecretVarId>,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
/// (state, vec![], vec![ZkStateChange::OpenVariables { variables: created_variables }])
/// }
/// ```
#[proc_macro_attribute]
pub fn zk_on_compute_complete(attrs: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(attrs as AttributeArgs);
let attributes = parse_attributes(
args,
vec!["shortname".to_string()],
vec!["shortname".to_string()],
);
let shortname_override = parse_shortname_override(&attributes);
let function_kind = WrappedFunctionKind {
output_state_and_events: true,
min_allowed_num_results: 1,
output_other_types: vec![(
quote! { Vec<pbc_contract_common::zk::ZkStateChange> },
format_ident!("write_zk_state_change"),
)],
system_arguments: 4,
fn_kind: FunctionKind::ZkComputeComplete,
allow_rpc_arguments: false,
};
zk_macro::handle_zk_macro(
input,
shortname_override,
Some(parse_quote! { pbc_contract_common::address::ShortnameZkComputeComplete }),
"zk_on_compute_complete",
&function_kind,
true,
SecretInput::None,
)
}
/// Secret variable opened zero-knowledge contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook, and is not required for a well-formed
/// zero-knowledge contract. The default behaviour is to do nothing.
///
/// If the annotated function panics changes to the contract state [will be rolled back](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Annotated function is automatically called when a contract opens one or more secret
/// variables; this can only happen after the use of
/// [`ZkStateChange::OpenVariables`](pbc_contract_common::zk::ZkStateChange::OpenVariables).
/// This hook is exclusively called by the blockchain itself, and cannot be called manually from
/// the dashboard, nor from another contract.
///
/// Allows the contract to automatically react to opening of ZK variables.
///
/// Annotated function must have a signature of following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_variables_opened]
/// pub fn zk_on_variables_opened(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// opened_variables: Vec<SecretVarId>,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>)
/// # { (state, vec![], vec![]) }
/// ```
///
/// Where `opened_variables` is a [`Vec`] of the opened variables.
///
/// # Example
///
/// Common usages include post-processing of computation results; for example
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = Vec<Vec<u8>>;
/// # type Metadata = u32;
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { vec![] }
/// #[zk_on_variables_opened]
/// pub fn zk_on_sum_variable_opened(
/// context: ContractContext,
/// mut state: ContractState,
/// zk_state: ZkState<Metadata>,
/// opened_variables: Vec<SecretVarId>,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
/// let result_var_id: SecretVarId = *opened_variables.get(0).unwrap();
/// let result_var: ZkClosed<Metadata> = zk_state.get_variable(result_var_id).unwrap();
/// let result: Vec<u8> = result_var.data.as_ref().unwrap().clone();
/// state.push(result);
/// (state, vec![], vec![])
/// }
/// ```
#[proc_macro_attribute]
pub fn zk_on_variables_opened(attrs: TokenStream, input: TokenStream) -> TokenStream {
assert!(
attrs.is_empty(),
"No attributes are supported for zk_on_variables_opened"
);
let function_kind = WrappedFunctionKind {
output_state_and_events: true,
min_allowed_num_results: 1,
output_other_types: vec![(
quote! { Vec<pbc_contract_common::zk::ZkStateChange> },
format_ident!("write_zk_state_change"),
)],
system_arguments: 4,
fn_kind: FunctionKind::ZkVarOpened,
allow_rpc_arguments: false,
};
zk_macro::handle_zk_macro(
input,
None,
None,
"zk_on_variables_opened",
&function_kind,
false,
SecretInput::None,
)
}
/// Data-attestation complete zero-knowledge contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook, and is not required for a well-formed
/// zero-knowledge contract. The default behaviour is to do nothing.
///
/// If the annotated function panics changes to the contract state [will be rolled back](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Annotated function is automatically called when the contract is informed of the availability of
/// signatures for attested data. This can only happen after the use of
/// [`ZkStateChange::Attest`](pbc_contract_common::zk::ZkStateChange::Attest). This hook is
/// exclusively called by the blockchain itself, and cannot be called manually from the dashboard,
/// nor from another contract.
///
/// Allows the contract to automatically react to data-attestations.
///
/// Annotated function must have a signature of following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// # type ContractState = u32;
/// # type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_attestation_complete]
/// pub fn zk_on_attestation_complete(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// attestation_id: AttestationId,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>)
/// # { (state, vec![], vec![]) }
/// ```
///
/// Where [`ZkState`](pbc_contract_common::zk::ZkState) can be further accessed to determine signatures, etc.
#[proc_macro_attribute]
pub fn zk_on_attestation_complete(attrs: TokenStream, input: TokenStream) -> TokenStream {
assert!(
attrs.is_empty(),
"No attributes are supported for zk_on_attestation_complete"
);
let function_kind = WrappedFunctionKind {
output_state_and_events: true,
min_allowed_num_results: 1,
output_other_types: vec![(
quote! { Vec<pbc_contract_common::zk::ZkStateChange> },
format_ident!("write_zk_state_change"),
)],
system_arguments: 4,
fn_kind: FunctionKind::ZkAttestationComplete,
allow_rpc_arguments: false,
};
zk_macro::handle_zk_macro(
input,
None,
None,
"zk_on_attestation_complete",
&function_kind,
false,
SecretInput::None,
)
}
/// External event zero-knowledge contract annotation
///
/// **OPTIONAL HOOK**: This is an optional hook, and is not required for a well-formed
/// zero-knowledge contract. The default behaviour is to do nothing.
///
/// If the annotated function panics changes to the contract state [will be rolled back](https://partisiablockchain.gitlab.io/documentation/smart-contracts/smart-contract-interactions-on-the-blockchain.html).
///
/// Annotated function is automatically called when the contract is informed of a new external event
/// that has been confirmed by the EVM oracle to have occurred on an external EVM chain. This can
/// only happen after the use of
/// [`ZkStateChange::SubscribeToEvmEvents`](pbc_contract_common::zk::ZkStateChange::SubscribeToEvmEvents).
/// This hook is exclusively called by the blockchain itself, and cannot be called manually from the
/// dashboard, nor from another contract.
///
/// Allows the contract to automatically react to EVM events.
///
/// Annotated function must have a signature of following format:
///
/// ```
/// # use pbc_contract_codegen::*;
/// # use pbc_contract_common::context::*;
/// # use pbc_contract_common::zk::*;
/// # use pbc_contract_common::events::*;
/// use pbc_contract_common::zk::evm_event::{ExternalEventId, EventSubscriptionId};
/// # type ContractState = u32;
/// # type Metadata = u32;
///
/// # #[init(zk = true)] pub fn initialize(context: ContractContext, zk_state: ZkState<Metadata>) -> ContractState { 0 }
///
/// #[zk_on_external_event]
/// pub fn zk_on_external_event(
/// context: ContractContext,
/// state: ContractState,
/// zk_state: ZkState<Metadata>,
/// subscription_id: EventSubscriptionId,
/// event_id: ExternalEventId,
/// ) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>)
/// # { (state, vec![], vec![]) }
/// ```
///
/// Where [`ZkState`](pbc_contract_common::zk::ZkState) can be further accessed to read the event, etc.
#[proc_macro_attribute]
pub fn zk_on_external_event(attrs: TokenStream, input: TokenStream) -> TokenStream {
assert!(
attrs.is_empty(),
"No attributes are supported for zk_on_external_event"
);
let function_kind = WrappedFunctionKind {
output_state_and_events: true,
min_allowed_num_results: 1,
output_other_types: vec![(
quote! { Vec<pbc_contract_common::zk::ZkStateChange> },
format_ident!("write_zk_state_change"),
)],
system_arguments: 5,
fn_kind: FunctionKind::ZkExternalEvent,
allow_rpc_arguments: false,
};
zk_macro::handle_zk_macro(
input,
None,
None,
"zk_on_external_event",
&function_kind,
false,
SecretInput::None,
)
}