Skip to main content

hiero_sdk/address_book/
node_create_transaction.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::net::Ipv4Addr;
4
5use hiero_sdk_proto::services;
6use hiero_sdk_proto::services::address_book_service_client::AddressBookServiceClient;
7use tonic::transport::Channel;
8
9use crate::ledger_id::RefLedgerId;
10use crate::protobuf::FromProtobuf;
11use crate::service_endpoint::ServiceEndpoint;
12use crate::transaction::{
13    AnyTransactionData,
14    ChunkInfo,
15    ToSchedulableTransactionDataProtobuf,
16    ToTransactionDataProtobuf,
17    TransactionData,
18    TransactionExecute,
19};
20use crate::{
21    AccountId,
22    BoxGrpcFuture,
23    Error,
24    Key,
25    ToProtobuf,
26    Transaction,
27    ValidateChecksums,
28};
29
30/// A transaction body to add a new consensus node to the network address book.
31///
32/// This transaction body SHALL be considered a "privileged transaction".
33///
34/// This message supports a transaction to create a new node in the network
35/// address book. The transaction, once complete, enables a new consensus node
36/// to join the network, and requires governing council authorization.
37pub type NodeCreateTransaction = Transaction<NodeCreateTransactionData>;
38
39/// A transaction body to add a new consensus node to the network address book.
40#[derive(Debug, Clone, Default)]
41pub struct NodeCreateTransactionData {
42    /// A Node account identifier.
43    account_id: Option<AccountId>,
44
45    /// A short description of the node.
46    description: String,
47
48    /// A list of service endpoints for gossip.
49    gossip_endpoints: Vec<ServiceEndpoint>,
50
51    /// A list of service endpoints for gRPC calls.
52    service_endpoints: Vec<ServiceEndpoint>,
53
54    /// A certificate used to sign gossip events.
55    gossip_ca_certificate: Vec<u8>,
56
57    /// A hash of the node gRPC TLS certificate.
58    grpc_certificate_hash: Vec<u8>,
59
60    /// An administrative key controlled by the node operator.
61    admin_key: Option<Key>,
62
63    decline_reward: bool,
64
65    grpc_proxy_endpoint: Option<ServiceEndpoint>,
66}
67
68impl NodeCreateTransaction {
69    /// Returns the account associated with the new node.
70    #[must_use]
71    pub fn get_account_id(&self) -> Option<AccountId> {
72        self.data().account_id
73    }
74
75    /// Sets the account associated with the new node.
76    pub fn account_id(&mut self, account_id: AccountId) -> &mut Self {
77        self.data_mut().account_id = Some(account_id);
78        self
79    }
80
81    /// Returns the description of the new node.
82    #[must_use]
83    pub fn get_description(&self) -> &str {
84        &self.data().description
85    }
86
87    /// Sets the description of the new node.
88    pub fn description(&mut self, description: impl Into<String>) -> &mut Self {
89        self.data_mut().description = description.into();
90        self
91    }
92
93    /// Returns the list of service endpoints for gossip.
94    #[must_use]
95    pub fn get_gossip_endpoints(&self) -> Vec<ServiceEndpoint> {
96        self.data().gossip_endpoints.clone()
97    }
98
99    /// Sets the list of service endpoints for gossip.
100    pub fn gossip_endpoints(
101        &mut self,
102        gossip_endpoint: impl IntoIterator<Item = ServiceEndpoint>,
103    ) -> &mut Self {
104        self.data_mut().gossip_endpoints = gossip_endpoint.into_iter().collect();
105        self
106    }
107
108    /// Adds a service endpoint for gossip to the list of service endpoints.
109    pub fn add_gossip_endpoint(&mut self, gossip_endpoint: ServiceEndpoint) -> &mut Self {
110        self.data_mut().gossip_endpoints.push(gossip_endpoint);
111        self
112    }
113
114    /// Returns the list of service endpoints for gRPC calls.
115    #[must_use]
116    pub fn get_service_endpoints(&self) -> Vec<ServiceEndpoint> {
117        self.data().service_endpoints.clone()
118    }
119
120    /// Sets the list of service endpoints for gRPC calls.
121    pub fn service_endpoints(
122        &mut self,
123        service_endpoint: impl IntoIterator<Item = ServiceEndpoint>,
124    ) -> &mut Self {
125        self.data_mut().service_endpoints = service_endpoint.into_iter().collect();
126        self
127    }
128
129    /// Adds a service endpoint to the list of service endpoints for gRPC calls.
130    pub fn add_service_endpoint(&mut self, service_endpoint: ServiceEndpoint) -> &mut Self {
131        self.data_mut().service_endpoints.push(service_endpoint);
132        self
133    }
134
135    /// Returns the certificate used to sign gossip events.
136    #[must_use]
137    pub fn get_gossip_ca_certificate(&self) -> &[u8] {
138        &self.data().gossip_ca_certificate
139    }
140
141    /// Sets the certificate used to sign gossip events.
142    pub fn gossip_ca_certificate(
143        &mut self,
144        gossip_ca_certificate: impl Into<Vec<u8>>,
145    ) -> &mut Self {
146        self.data_mut().gossip_ca_certificate = gossip_ca_certificate.into();
147        self
148    }
149
150    /// Returns the hash of the node gRPC TLS certificate.
151    #[must_use]
152    pub fn get_grpc_certificate_hash(&self) -> &[u8] {
153        &self.data().grpc_certificate_hash
154    }
155
156    /// Sets the hash of the node gRPC TLS certificate.
157    pub fn grpc_certificate_hash(
158        &mut self,
159        grpc_certificate_hash: impl Into<Vec<u8>>,
160    ) -> &mut Self {
161        self.data_mut().grpc_certificate_hash = grpc_certificate_hash.into();
162        self
163    }
164
165    /// Returns the admin key.
166    #[must_use]
167    pub fn get_admin_key(&self) -> Option<&Key> {
168        self.data().admin_key.as_ref()
169    }
170
171    /// Sets the admin key.
172    pub fn admin_key(&mut self, key: impl Into<Key>) -> &mut Self {
173        self.data_mut().admin_key = Some(key.into());
174        self
175    }
176
177    /// Returns the decline reward.
178    #[must_use]
179    pub fn get_decline_reward(&self) -> bool {
180        self.data().decline_reward
181    }
182
183    /// Sets the decline reward.
184    pub fn decline_reward(&mut self, decline_reward: bool) -> &mut Self {
185        self.data_mut().decline_reward = decline_reward;
186        self
187    }
188
189    /// Returns the grpc proxy endpoint.
190    #[must_use]
191    pub fn get_grpc_proxy_endpoint(&self) -> Option<&ServiceEndpoint> {
192        self.data().grpc_proxy_endpoint.as_ref()
193    }
194
195    /// Sets the grpc proxy endpoint.
196    pub fn grpc_proxy_endpoint(&mut self, grpc_proxy_endpoint: ServiceEndpoint) -> &mut Self {
197        self.data_mut().grpc_proxy_endpoint = Some(grpc_proxy_endpoint);
198        self
199    }
200}
201
202impl TransactionData for NodeCreateTransactionData {}
203
204impl TransactionExecute for NodeCreateTransactionData {
205    fn execute(
206        &self,
207        channel: Channel,
208        request: services::Transaction,
209    ) -> BoxGrpcFuture<'_, services::TransactionResponse> {
210        Box::pin(async { AddressBookServiceClient::new(channel).create_node(request).await })
211    }
212}
213
214impl ValidateChecksums for NodeCreateTransactionData {
215    fn validate_checksums(&self, ledger_id: &RefLedgerId) -> Result<(), Error> {
216        self.account_id.validate_checksums(ledger_id)?;
217        Ok(())
218    }
219}
220
221impl ToTransactionDataProtobuf for NodeCreateTransactionData {
222    fn to_transaction_data_protobuf(
223        &self,
224        chunk_info: &ChunkInfo,
225    ) -> services::transaction_body::Data {
226        let _ = chunk_info.assert_single_transaction();
227
228        services::transaction_body::Data::NodeCreate(self.to_protobuf())
229    }
230}
231
232impl ToSchedulableTransactionDataProtobuf for NodeCreateTransactionData {
233    fn to_schedulable_transaction_data_protobuf(
234        &self,
235    ) -> services::schedulable_transaction_body::Data {
236        services::schedulable_transaction_body::Data::NodeCreate(self.to_protobuf())
237    }
238}
239
240impl From<NodeCreateTransactionData> for AnyTransactionData {
241    fn from(transaction: NodeCreateTransactionData) -> Self {
242        Self::NodeCreate(transaction)
243    }
244}
245
246impl FromProtobuf<services::NodeCreateTransactionBody> for NodeCreateTransactionData {
247    fn from_protobuf(pb: services::NodeCreateTransactionBody) -> crate::Result<Self> {
248        let gossip_endpoints = pb
249            .gossip_endpoint
250            .iter()
251            .map(|it| {
252                let ip_addr_v4 = &it.ip_address_v4[..];
253                let ip = Ipv4Addr::new(ip_addr_v4[0], ip_addr_v4[1], ip_addr_v4[2], ip_addr_v4[3]);
254                ServiceEndpoint {
255                    ip_address_v4: Some(ip),
256                    port: it.port,
257                    domain_name: it.domain_name.clone(),
258                }
259            })
260            .collect();
261        let service_endpoints = pb
262            .service_endpoint
263            .iter()
264            .map(|it| {
265                let ip_addr_v4 = &it.ip_address_v4[..];
266                let ip = Ipv4Addr::new(ip_addr_v4[0], ip_addr_v4[1], ip_addr_v4[2], ip_addr_v4[3]);
267                ServiceEndpoint {
268                    ip_address_v4: Some(ip),
269                    port: it.port,
270                    domain_name: it.domain_name.clone(),
271                }
272            })
273            .collect();
274
275        Ok(Self {
276            account_id: FromProtobuf::from_protobuf(pb.account_id)?,
277            description: pb.description,
278            gossip_endpoints: gossip_endpoints,
279            service_endpoints: service_endpoints,
280            gossip_ca_certificate: pb.gossip_ca_certificate,
281            grpc_certificate_hash: pb.grpc_certificate_hash,
282            admin_key: Option::from_protobuf(pb.admin_key)?,
283            decline_reward: pb.decline_reward,
284            grpc_proxy_endpoint: pb.grpc_proxy_endpoint.map(|it| ServiceEndpoint {
285                ip_address_v4: Some(Ipv4Addr::new(
286                    it.ip_address_v4[0],
287                    it.ip_address_v4[1],
288                    it.ip_address_v4[2],
289                    it.ip_address_v4[3],
290                )),
291                port: it.port,
292                domain_name: it.domain_name.clone(),
293            }),
294        })
295    }
296}
297
298impl ToProtobuf for NodeCreateTransactionData {
299    type Protobuf = services::NodeCreateTransactionBody;
300
301    fn to_protobuf(&self) -> Self::Protobuf {
302        let gossip_endpoints =
303            self.gossip_endpoints.iter().map(|it| it.to_protobuf()).collect::<Vec<_>>();
304        let service_endpoints =
305            self.service_endpoints.iter().map(|it| it.to_protobuf()).collect::<Vec<_>>();
306
307        services::NodeCreateTransactionBody {
308            account_id: self.account_id.to_protobuf(),
309            description: self.description.clone(),
310            gossip_endpoint: gossip_endpoints,
311            service_endpoint: service_endpoints,
312            gossip_ca_certificate: self.gossip_ca_certificate.clone(),
313            grpc_certificate_hash: self.grpc_certificate_hash.clone(),
314            admin_key: self.admin_key.to_protobuf(),
315            decline_reward: self.decline_reward,
316            grpc_proxy_endpoint: self.grpc_proxy_endpoint.as_ref().map(|it| it.to_protobuf()),
317            associated_registered_node: Vec::new(),
318        }
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use std::net::Ipv4Addr;
325
326    use expect_test::expect_file;
327    use hiero_sdk_proto::services;
328
329    use super::NodeCreateTransaction;
330    use crate::address_book::NodeCreateTransactionData;
331    use crate::protobuf::{
332        FromProtobuf,
333        ToProtobuf,
334    };
335    use crate::service_endpoint::ServiceEndpoint;
336    use crate::transaction::test_helpers::{
337        check_body,
338        transaction_body,
339        unused_private_key,
340        TEST_ACCOUNT_ID,
341    };
342    use crate::{
343        AnyTransaction,
344        Key,
345    };
346
347    const TEST_DESCRIPTION: &str = "test description";
348    const TEST_GOSSIP_CA_CERTIFICATE: &[u8] = &[1, 2, 3, 4];
349    const TEST_GRPC_CERTIFICATE_HASH: &[u8] = &[5, 6, 7, 8];
350
351    fn make_ip_address_list() -> Vec<ServiceEndpoint> {
352        vec![ServiceEndpoint {
353            ip_address_v4: Some(Ipv4Addr::new(127, 0, 0, 1)),
354            port: 1234,
355            domain_name: "".to_owned(),
356        }]
357    }
358
359    fn make_transaction() -> NodeCreateTransaction {
360        let mut tx = NodeCreateTransaction::new_for_tests();
361
362        tx.account_id(TEST_ACCOUNT_ID)
363            .description(TEST_DESCRIPTION)
364            .gossip_endpoints(make_ip_address_list())
365            .service_endpoints(make_ip_address_list())
366            .gossip_ca_certificate(TEST_GOSSIP_CA_CERTIFICATE)
367            .grpc_certificate_hash(TEST_GRPC_CERTIFICATE_HASH)
368            .admin_key(unused_private_key().public_key())
369            .freeze()
370            .unwrap();
371
372        tx
373    }
374
375    #[test]
376    fn serialize() {
377        let tx = make_transaction();
378
379        let tx = transaction_body(tx);
380
381        let tx = check_body(tx);
382
383        expect_file!["./snapshots/node_create_transaction/serialize.txt"].assert_debug_eq(&tx);
384    }
385
386    #[test]
387    fn to_from_bytes() {
388        let tx = make_transaction();
389
390        let tx2 = AnyTransaction::from_bytes(&tx.to_bytes().unwrap()).unwrap();
391
392        let tx = transaction_body(tx);
393        let tx2 = transaction_body(tx2);
394
395        assert_eq!(tx, tx2)
396    }
397
398    #[test]
399    fn from_proto_body() {
400        let tx = services::NodeCreateTransactionBody {
401            account_id: Some(TEST_ACCOUNT_ID.to_protobuf()),
402            description: TEST_DESCRIPTION.to_owned(),
403            gossip_endpoint: make_ip_address_list()
404                .into_iter()
405                .map(|it| it.to_protobuf())
406                .collect(),
407            service_endpoint: make_ip_address_list()
408                .into_iter()
409                .map(|it| it.to_protobuf())
410                .collect(),
411            gossip_ca_certificate: TEST_GOSSIP_CA_CERTIFICATE.to_vec(),
412            grpc_certificate_hash: TEST_GRPC_CERTIFICATE_HASH.to_vec(),
413            admin_key: Some(unused_private_key().public_key().to_protobuf()),
414            decline_reward: false,
415            grpc_proxy_endpoint: None,
416            associated_registered_node: Vec::new(),
417        };
418
419        let data = NodeCreateTransactionData::from_protobuf(tx).unwrap();
420
421        assert_eq!(data.account_id, Some(TEST_ACCOUNT_ID));
422        assert_eq!(data.description, TEST_DESCRIPTION);
423        assert_eq!(data.gossip_endpoints, make_ip_address_list());
424        assert_eq!(data.service_endpoints, make_ip_address_list());
425        assert_eq!(data.gossip_ca_certificate, TEST_GOSSIP_CA_CERTIFICATE);
426        assert_eq!(data.grpc_certificate_hash, TEST_GRPC_CERTIFICATE_HASH);
427        assert_eq!(data.admin_key, Some(Key::from(unused_private_key().public_key())));
428    }
429
430    #[test]
431    fn get_set_account_id() {
432        let account_id = TEST_ACCOUNT_ID;
433        let mut tx = NodeCreateTransaction::new();
434        tx.account_id(account_id.to_owned());
435
436        assert_eq!(tx.get_account_id(), Some(account_id));
437    }
438
439    #[test]
440    #[should_panic]
441    fn get_set_account_id_frozen_panic() {
442        make_transaction().account_id(TEST_ACCOUNT_ID);
443    }
444
445    #[test]
446    fn get_set_description() {
447        let description = TEST_DESCRIPTION.to_owned();
448        let mut tx = NodeCreateTransaction::new();
449        tx.description(description.to_owned());
450
451        assert_eq!(tx.get_description(), TEST_DESCRIPTION);
452    }
453
454    #[test]
455    #[should_panic]
456    fn get_set_description_frozen_panic() {
457        make_transaction().description(TEST_DESCRIPTION);
458    }
459
460    #[test]
461    fn get_set_gossip_endpoints() {
462        let gossip_endpoints = make_ip_address_list();
463        let mut tx = NodeCreateTransaction::new();
464        tx.gossip_endpoints(gossip_endpoints.to_owned());
465
466        assert_eq!(tx.get_gossip_endpoints(), gossip_endpoints);
467    }
468
469    #[test]
470    #[should_panic]
471    fn get_set_gossip_endpoint_frozen_panic() {
472        make_transaction().gossip_endpoints(make_ip_address_list());
473    }
474
475    #[test]
476    fn get_set_service_endpoints() {
477        let service_endpoints = make_ip_address_list();
478        let mut tx = NodeCreateTransaction::new();
479        tx.service_endpoints(service_endpoints.to_owned());
480
481        assert_eq!(tx.get_service_endpoints(), service_endpoints);
482    }
483
484    #[test]
485    #[should_panic]
486    fn get_set_service_endpoints_frozen_panic() {
487        make_transaction().service_endpoints(make_ip_address_list());
488    }
489
490    #[test]
491    fn get_set_grpc_certificate_hash() {
492        let mut tx = NodeCreateTransaction::new();
493        tx.grpc_certificate_hash(TEST_GOSSIP_CA_CERTIFICATE);
494
495        assert_eq!(tx.get_grpc_certificate_hash(), TEST_GOSSIP_CA_CERTIFICATE);
496    }
497
498    #[test]
499    #[should_panic]
500    fn get_set_grpc_certificate_hash_frozen_panic() {
501        make_transaction().grpc_certificate_hash(TEST_GOSSIP_CA_CERTIFICATE);
502    }
503
504    #[test]
505    fn get_set_admin_key() {
506        let mut tx = NodeCreateTransaction::new();
507        tx.admin_key(unused_private_key().public_key());
508
509        assert_eq!(tx.get_admin_key(), Some(&Key::from(unused_private_key().public_key())));
510    }
511
512    #[test]
513    #[should_panic]
514    fn get_set_admin_key_frozen_panic() {
515        make_transaction().admin_key(Key::from(unused_private_key().public_key()));
516    }
517
518    #[test]
519    fn get_set_decline_reward() {
520        let mut tx = NodeCreateTransaction::new();
521        tx.decline_reward(true);
522
523        assert_eq!(tx.get_decline_reward(), true);
524    }
525
526    #[test]
527    fn get_set_grpc_proxy_endpoint() {
528        let grpc_proxy_endpoint = make_ip_address_list().into_iter().next().unwrap();
529        let mut tx = NodeCreateTransaction::new();
530        tx.grpc_proxy_endpoint(grpc_proxy_endpoint.clone());
531
532        assert_eq!(tx.get_grpc_proxy_endpoint(), Some(&grpc_proxy_endpoint));
533    }
534}