Diff
Not logged in

Differences From Artifact [986eee6533]:

To Artifact [a7e38ad771]:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
..
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
..
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
...
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
...
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
...
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
...
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
...
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
...
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
...
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
...
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
....
1156
1157
1158
1159
1160
1161
1162

1163
1164

1165
1166
1167
1168
1169
1170
1171
....
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
// Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0.  This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
................................................................................
use ffi::low_level_api::object_cache::object_cache;
use routing::{AppendWrapper, AppendedData, Data, Filter, PrivAppendableData, PrivAppendedData,
              PubAppendableData, XOR_NAME_LEN, XorName};
use std::{mem, ptr};
use std::collections::BTreeSet;
use std::iter;

/// Wrapper for PrivAppendableData and PubAppendableData.
#[derive(Clone, Debug, Hash)]
pub enum AppendableData {
    /// Public appendable data.
    Pub(PubAppendableData),
    /// Private appendable data.
    Priv(PrivAppendableData),
}
................................................................................
pub enum FilterType {
    /// BlackList
    BlackList,
    /// WhiteList
    WhiteList,
}

/// Create new PubAppendableData
#[no_mangle]
pub unsafe extern "C" fn appendable_data_new_pub(app: *const App,
                                                 name: *const [u8; XOR_NAME_LEN],
                                                 o_handle: *mut AppendableDataHandle)
                                                 -> i32 {
    helper::catch_unwind_i32(|| {
        let client = (*app).get_client();
................................................................................
        owners.insert(owner_key);

        let mut data = ffi_try!(PubAppendableData::new(name,
                                                       0,
                                                       owners,
                                                       Default::default(),
                                                       Filter::black_list(iter::empty()))
            .map_err(CoreError::from));
        let _ = ffi_try!(data.add_signature(&(owner_key, private_signing_key))
            .map_err(CoreError::from));

        let handle = unwrap!(object_cache()).insert_ad(AppendableData::Pub(data));

        ptr::write(o_handle, handle);
        0
    })
}

/// Create new PrivAppendableData
#[no_mangle]
pub unsafe extern "C" fn appendable_data_new_priv(app: *const App,
                                                  name: *const [u8; XOR_NAME_LEN],
                                                  o_handle: *mut AppendableDataHandle)
                                                  -> i32 {
    helper::catch_unwind_i32(|| {
        let app = &*app;
................................................................................

        let mut data = ffi_try!(PrivAppendableData::new(name,
                                                        0,
                                                        owners,
                                                        Default::default(),
                                                        Filter::black_list(iter::empty()),
                                                        ffi_try!(app.asym_keys()).0)
            .map_err(CoreError::from));
        let _ = ffi_try!(data.add_signature(&(owner_key, private_signing_key))
            .map_err(CoreError::from));

        let handle = unwrap!(object_cache()).insert_ad(AppendableData::Priv(data));

        ptr::write(o_handle, handle);
        0
    })
}
................................................................................
        let handle = unwrap!(object_cache()).insert_ad(data);

        ptr::write(o_handle, handle);
        0
    })
}

/// Extract DataIdentifier from AppendableData.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_extract_data_id(ad_h: AppendableDataHandle,
                                                         o_handle: *mut DataIdHandle)
                                                         -> i32 {
    helper::catch_unwind_i32(|| {
        let mut object_cache = unwrap!(object_cache());
        let data_id = match *ffi_try!(object_cache.get_ad(ad_h)) {
................................................................................

        let new_ad = {
            let mut object_cache = unwrap!(object_cache());
            let ad = ffi_try!(object_cache.get_ad(ad_h));

            match *ad {
                AppendableData::Pub(ref old_data) => {

                    let mut new_data = ffi_try!(PubAppendableData::new(old_data.name,
                                                                       old_data.version + 1,
                                                                       old_data.owners.clone(),
                                                                       old_data.deleted_data
                                                                           .clone(),
                                                                       old_data.filter.clone())
                        .map_err(CoreError::from));
                    if include_data {
                        new_data.data = old_data.data.clone();
                    }
                    let owner_key = *ffi_try!(unwrap!(client.lock()).get_public_signing_key());
                    let private_signing_key =
                        ffi_try!(unwrap!(client.lock()).get_secret_signing_key()).clone();

                    let _ = ffi_try!(new_data.add_signature(&(owner_key, private_signing_key))
                        .map_err(CoreError::from));
                    AppendableData::Pub(new_data)
                }
                AppendableData::Priv(ref old_data) => {
                    let mut new_data =
                        ffi_try!(PrivAppendableData::new(old_data.name,
                                                         old_data.version + 1,
                                                         old_data.owners.clone(),
                                                         old_data.deleted_data.clone(),
                                                         old_data.filter.clone(),
                                                         old_data.encrypt_key.clone())
                            .map_err(CoreError::from));
                    if include_data {
                        new_data.data = old_data.data.clone();
                    }
                    let owner_key = *ffi_try!(unwrap!(client.lock()).get_public_signing_key());
                    let private_signing_key =
                        ffi_try!(unwrap!(client.lock()).get_secret_signing_key()).clone();

                    let _ = ffi_try!(new_data.add_signature(&(owner_key, private_signing_key))
                        .map_err(CoreError::from));
                    AppendableData::Priv(new_data)
                }
            }
        };
        let resp_getter = ffi_try!(unwrap!(client.lock()).post(new_ad.clone().into(), None));
        ffi_try!(resp_getter.get());
        *ffi_try!(unwrap!(object_cache()).get_ad(ad_h)) = new_ad;
................................................................................
#[no_mangle]
pub unsafe extern "C" fn appendable_data_encrypt_key(ad_h: AppendableDataHandle,
                                                     o_handle: *mut EncryptKeyHandle)
                                                     -> i32 {
    helper::catch_unwind_i32(|| {
        let mut object_cache = unwrap!(object_cache());
        let pk = match *ffi_try!(object_cache.get_ad(ad_h)) {
            AppendableData::Priv(ref elt) => elt.encrypt_key.clone(),
            _ => ffi_try!(Err(FfiError::UnsupportedOperation)),
        };
        let handle = object_cache.insert_encrypt_key(pk);
        ptr::write(o_handle, handle);
        0
    })
}
................................................................................

/// Get number of appended data items.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_num_of_data(ad_h: AppendableDataHandle,
                                                     o_num: *mut usize)
                                                     -> i32 {
    helper::catch_unwind_i32(|| {
        ffi_try!(appendable_data_num_of_data_impl(ad_h, false, o_num));
        0
    })
}

/// Get number of appended deleted data items.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_num_of_deleted_data(ad_h: AppendableDataHandle,
                                                             o_num: *mut usize)
                                                             -> i32 {
    helper::catch_unwind_i32(|| {
        ffi_try!(appendable_data_num_of_data_impl(ad_h, true, o_num));
        0
    })
}

unsafe fn appendable_data_num_of_data_impl(ad_h: AppendableDataHandle,
                                           is_deleted_data: bool,
                                           o_num: *mut usize)
                                           -> Result<(), FfiError> {
    let mut object_cache = unwrap!(object_cache());
    let ad = try!(object_cache.get_ad(ad_h));
    let num = match *ad {
        AppendableData::Pub(ref elt) => {
            if is_deleted_data {
                elt.deleted_data.len()
            } else {
                elt.data.len()
            }
................................................................................
        }
    };

    ptr::write(o_num, num);
    Ok(())
}

/// Get nth appended DataIdentifier from data.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_data_id(app: *const App,
                                                     ad_h: AppendableDataHandle,
                                                     n: usize,
                                                     o_handle: *mut DataIdHandle)
                                                     -> i32 {
    helper::catch_unwind_i32(|| {
        ffi_try!(appendable_data_nth_data_id_impl(app, ad_h, n, false, o_handle));




        0
    })
}

/// Get nth appended DataIdentifier from deleted data.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_deleted_data_id(app: *const App,
                                                             ad_h: AppendableDataHandle,
                                                             n: usize,
                                                             o_handle: *mut DataIdHandle)
                                                             -> i32 {
    helper::catch_unwind_i32(|| {
        ffi_try!(appendable_data_nth_data_id_impl(app, ad_h, n, true, o_handle));




        0
    })
}

unsafe fn appendable_data_nth_data_id_impl(app: *const App,
                                           ad_h: AppendableDataHandle,
                                           n: usize,
                                           is_deleted_data: bool,
                                           o_handle: *mut DataIdHandle)
                                           -> Result<(), FfiError> {
    let app = &*app;

    let mut object_cache = unwrap!(object_cache());

    let data_id = match *try!(object_cache.get_ad(ad_h)) {
        AppendableData::Priv(ref elt) => {
            let priv_data = if is_deleted_data {
                try!(nth(&elt.deleted_data, n))
            } else {
                try!(nth(&elt.data, n))
            };
            let &(ref pk, ref sk) = try!(app.asym_keys());


            try!(priv_data.open(pk, sk).map_err(CoreError::from)).pointer


        }
        AppendableData::Pub(ref elt) => {
            if is_deleted_data {
                try!(nth(&elt.deleted_data, n)).pointer
            } else {
                try!(nth(&elt.data, n)).pointer
            }
        }
    };

    let handle = object_cache.insert_data_id(data_id);

    ptr::write(o_handle, handle);
................................................................................
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_data_sign_key(app: *const App,
                                                           ad_h: AppendableDataHandle,
                                                           n: usize,
                                                           o_handle: *mut SignKeyHandle)
                                                           -> i32 {
    helper::catch_unwind_i32(|| {
        ffi_try!(appendable_data_nth_sign_key_impl(app, ad_h, n, false, o_handle));




        0
    })
}

/// Get nth sign key from deleted data
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_deleted_data_sign_key(app: *const App,
                                                                   ad_h: AppendableDataHandle,
                                                                   n: usize,
                                                                   o_handle: *mut SignKeyHandle)
                                                                   -> i32 {
    helper::catch_unwind_i32(|| {
        ffi_try!(appendable_data_nth_sign_key_impl(app, ad_h, n, true, o_handle));




        0
    })
}

unsafe fn appendable_data_nth_sign_key_impl(app: *const App,
                                            ad_h: AppendableDataHandle,
                                            n: usize,
                                            is_deleted_data: bool,
                                            o_handle: *mut SignKeyHandle)
                                            -> Result<(), FfiError> {
    let app = &*app;

    let mut object_cache = unwrap!(object_cache());

    let sign_key = match *try!(object_cache.get_ad(ad_h)) {
        AppendableData::Priv(ref elt) => {
            let priv_data = if is_deleted_data {
                try!(nth(&elt.deleted_data, n))
            } else {
                try!(nth(&elt.data, n))
            };
            let &(ref pk, ref sk) = try!(app.asym_keys());


            try!(priv_data.open(pk, sk).map_err(CoreError::from)).sign_key


        }
        AppendableData::Pub(ref elt) => {
            if is_deleted_data {
                try!(nth(&elt.deleted_data, n)).sign_key
            } else {
                try!(nth(&elt.data, n)).sign_key
            }
        }
    };

    let handle = object_cache.insert_sign_key(sign_key);

    ptr::write(o_handle, handle);
................................................................................
            let data_id = *ffi_try!(object_cache.get_data_id(data_id_h));

            let client = unwrap!(client.lock());
            let sign_pk = ffi_try!(client.get_public_signing_key());
            let sign_sk = ffi_try!(client.get_secret_signing_key());

            let appended_data = ffi_try!(AppendedData::new(data_id, *sign_pk, sign_sk)
                .map_err(CoreError::from));

            match *ffi_try!(object_cache.get_ad(ad_h)) {
                AppendableData::Priv(ref elt) => {
                    let priv_appended_data = ffi_try!(PrivAppendedData::new(&appended_data,
                                                                            &elt.encrypt_key)
                        .map_err(CoreError::from));
                    ffi_try!(AppendWrapper::new_priv(elt.name,
                                                     priv_appended_data,
                                                     (sign_pk, sign_sk),
                                                     elt.version)
                        .map_err(CoreError::from))
                }
                AppendableData::Pub(ref elt) => {
                    AppendWrapper::new_pub(elt.name, appended_data, elt.version)
                }
            }
        };

................................................................................
        let resp_getter = ffi_try!(unwrap!(client.lock()).append(append_wrapper, None));
        ffi_try!(resp_getter.get());

        0
    })
}

/// Get the current version of AppendableData by its handle
#[no_mangle]
pub unsafe extern "C" fn appendable_data_version(handle: AppendableDataHandle,
                                                 o_version: *mut u64)
                                                 -> i32 {
    helper::catch_unwind_i32(|| {
        *o_version = match *ffi_try!(unwrap!(object_cache()).get_ad(handle)) {
            AppendableData::Pub(ref mut elt) => elt.get_version(),
................................................................................
            AppendableData::Priv(ref mut elt) => elt.get_version(),
        };

        0
    })
}

/// See if AppendableData size is valid.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_validate_size(handle: AppendableDataHandle,
                                                       o_valid: *mut bool)
                                                       -> i32 {
    helper::catch_unwind_i32(|| {
        *o_valid = match *ffi_try!(unwrap!(object_cache()).get_ad(handle)) {
            AppendableData::Pub(ref elt) => elt.validate_size(),
................................................................................
            AppendableData::Priv(ref elt) => elt.validate_size(),
        };

        0
    })
}

/// Returns true if the app is one of the owners of the provided AppendableData.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_is_owned(app: *const App,
                                                  handle: AppendableDataHandle,
                                                  o_is_owned: *mut bool)
                                                  -> i32 {
    helper::catch_unwind_i32(|| {
        let client = (*app).get_client();
................................................................................
            AppendableData::Priv(ref mut elt) => elt.get_owners().contains(&my_key),
        };

        0
    })
}

/// Free AppendableData handle
#[no_mangle]
pub extern "C" fn appendable_data_free(handle: AppendableDataHandle) -> i32 {
    helper::catch_unwind_i32(|| {
        let _ = ffi_try!(unwrap!(object_cache()).remove_ad(handle));
        0
    })
}

// Convenience function to access n-th item from the given set, returning FfiError::InvalidIndex
// if not found.
fn nth<T>(items: &BTreeSet<T>, n: usize) -> Result<&T, FfiError> {
    items.iter().nth(n).ok_or(FfiError::InvalidIndex)
}

#[cfg(test)]
mod tests {

    use ffi::app::App;
    use ffi::errors::FfiError;
    use ffi::low_level_api::{AppendableDataHandle, DataIdHandle};
    use ffi::low_level_api::misc::*;
    use ffi::low_level_api::object_cache::object_cache;
    use ffi::test_utils;
    use rand;
    use routing::DataIdentifier;
    use rust_sodium::crypto::sign;
    use std::collections::HashSet;
    use super::*;

    macro_rules! assert_num_of_data {
        ($ad_h:ident, $expected:expr) => {
            let mut num: usize = 0;
            assert_eq!(appendable_data_num_of_data($ad_h, &mut num), 0);
            assert_eq!(num, $expected);
        }
................................................................................

        unsafe {
            // Initialise public appendable data
            let mut ad_h = 0;
            assert_eq!(appendable_data_new_pub(&app, &rand::random(), &mut ad_h), 0);

            // Public appendable data doens't have a private owner key

            assert_eq!(appendable_data_encrypt_key(ad_h, &mut encrypt_key_h),
                       FfiError::UnsupportedOperation.into());


            assert_eq!(appendable_data_free(ad_h), 0);

            // Initialise private appendable data
            let mut ad_h = 0;
            assert_eq!(appendable_data_new_priv(&app, &rand::random(), &mut ad_h),
                       0);
................................................................................

        (id, id_h)
    }

    fn get_sign_pk(app: &App) -> sign::PublicKey {
        let client = app.get_client();
        let client = unwrap!(client.lock());
        unwrap!(client.get_public_signing_key()).clone()
    }

    fn reload_ad(app: &App, ad_id_h: DataIdHandle, ad_h: &mut AppendableDataHandle) {
        assert_eq!(appendable_data_free(*ad_h), 0);
        unsafe {
            assert_eq!(appendable_data_get(app, ad_id_h, ad_h), 0);
        }
    }
}







|
|







 







|







 







|







 







|

|








|







 







|

|







 







|







 







>
|
|
|
|
<
|
|






>
|
|










|






>
|
|







 







|







 







|
|
|








|
|
|







|







 







|







|
>
>
>
>
|
|


|







|
>
>
>
>
|
|












|


|

|

|
>
>
|
>




|

|







 







|
>
>
>
>
|
|










|
>
>
>
>
|
|












|


|

|

|
>
>
|
>




|

|







 







|





|




|







 







|







 







|







 







|







 







|



|
|
|










>










<







 







>

<
>







 







|









1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
..
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
..
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
...
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
...
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
...
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
...
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
...
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
...
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
...
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
...
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
....
1180
1181
1182
1183
1184
1185
1186
1187
1188

1189
1190
1191
1192
1193
1194
1195
1196
....
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
// Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement.  This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
................................................................................
use ffi::low_level_api::object_cache::object_cache;
use routing::{AppendWrapper, AppendedData, Data, Filter, PrivAppendableData, PrivAppendedData,
              PubAppendableData, XOR_NAME_LEN, XorName};
use std::{mem, ptr};
use std::collections::BTreeSet;
use std::iter;

/// Wrapper for `PrivAppendableData` and `PubAppendableData`.
#[derive(Clone, Debug, Hash)]
pub enum AppendableData {
    /// Public appendable data.
    Pub(PubAppendableData),
    /// Private appendable data.
    Priv(PrivAppendableData),
}
................................................................................
pub enum FilterType {
    /// BlackList
    BlackList,
    /// WhiteList
    WhiteList,
}

/// Create new `PubAppendableData`
#[no_mangle]
pub unsafe extern "C" fn appendable_data_new_pub(app: *const App,
                                                 name: *const [u8; XOR_NAME_LEN],
                                                 o_handle: *mut AppendableDataHandle)
                                                 -> i32 {
    helper::catch_unwind_i32(|| {
        let client = (*app).get_client();
................................................................................
        owners.insert(owner_key);

        let mut data = ffi_try!(PubAppendableData::new(name,
                                                       0,
                                                       owners,
                                                       Default::default(),
                                                       Filter::black_list(iter::empty()))
                                        .map_err(CoreError::from));
        let _ = ffi_try!(data.add_signature(&(owner_key, private_signing_key))
                             .map_err(CoreError::from));

        let handle = unwrap!(object_cache()).insert_ad(AppendableData::Pub(data));

        ptr::write(o_handle, handle);
        0
    })
}

/// Create new `PrivAppendableData`
#[no_mangle]
pub unsafe extern "C" fn appendable_data_new_priv(app: *const App,
                                                  name: *const [u8; XOR_NAME_LEN],
                                                  o_handle: *mut AppendableDataHandle)
                                                  -> i32 {
    helper::catch_unwind_i32(|| {
        let app = &*app;
................................................................................

        let mut data = ffi_try!(PrivAppendableData::new(name,
                                                        0,
                                                        owners,
                                                        Default::default(),
                                                        Filter::black_list(iter::empty()),
                                                        ffi_try!(app.asym_keys()).0)
                                        .map_err(CoreError::from));
        let _ = ffi_try!(data.add_signature(&(owner_key, private_signing_key))
                             .map_err(CoreError::from));

        let handle = unwrap!(object_cache()).insert_ad(AppendableData::Priv(data));

        ptr::write(o_handle, handle);
        0
    })
}
................................................................................
        let handle = unwrap!(object_cache()).insert_ad(data);

        ptr::write(o_handle, handle);
        0
    })
}

/// Extract `DataIdentifier` from `AppendableData`.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_extract_data_id(ad_h: AppendableDataHandle,
                                                         o_handle: *mut DataIdHandle)
                                                         -> i32 {
    helper::catch_unwind_i32(|| {
        let mut object_cache = unwrap!(object_cache());
        let data_id = match *ffi_try!(object_cache.get_ad(ad_h)) {
................................................................................

        let new_ad = {
            let mut object_cache = unwrap!(object_cache());
            let ad = ffi_try!(object_cache.get_ad(ad_h));

            match *ad {
                AppendableData::Pub(ref old_data) => {
                    let mut new_data =
                        ffi_try!(PubAppendableData::new(old_data.name,
                                                        old_data.version + 1,
                                                        old_data.owners.clone(),
                                                        old_data.deleted_data.clone(),

                                                        old_data.filter.clone())
                                         .map_err(CoreError::from));
                    if include_data {
                        new_data.data = old_data.data.clone();
                    }
                    let owner_key = *ffi_try!(unwrap!(client.lock()).get_public_signing_key());
                    let private_signing_key =
                        ffi_try!(unwrap!(client.lock()).get_secret_signing_key()).clone();
                    let _ = ffi_try!(new_data
                                         .add_signature(&(owner_key, private_signing_key))
                                         .map_err(CoreError::from));
                    AppendableData::Pub(new_data)
                }
                AppendableData::Priv(ref old_data) => {
                    let mut new_data =
                        ffi_try!(PrivAppendableData::new(old_data.name,
                                                         old_data.version + 1,
                                                         old_data.owners.clone(),
                                                         old_data.deleted_data.clone(),
                                                         old_data.filter.clone(),
                                                         old_data.encrypt_key.clone())
                                         .map_err(CoreError::from));
                    if include_data {
                        new_data.data = old_data.data.clone();
                    }
                    let owner_key = *ffi_try!(unwrap!(client.lock()).get_public_signing_key());
                    let private_signing_key =
                        ffi_try!(unwrap!(client.lock()).get_secret_signing_key()).clone();
                    let _ = ffi_try!(new_data
                                         .add_signature(&(owner_key, private_signing_key))
                                         .map_err(CoreError::from));
                    AppendableData::Priv(new_data)
                }
            }
        };
        let resp_getter = ffi_try!(unwrap!(client.lock()).post(new_ad.clone().into(), None));
        ffi_try!(resp_getter.get());
        *ffi_try!(unwrap!(object_cache()).get_ad(ad_h)) = new_ad;
................................................................................
#[no_mangle]
pub unsafe extern "C" fn appendable_data_encrypt_key(ad_h: AppendableDataHandle,
                                                     o_handle: *mut EncryptKeyHandle)
                                                     -> i32 {
    helper::catch_unwind_i32(|| {
        let mut object_cache = unwrap!(object_cache());
        let pk = match *ffi_try!(object_cache.get_ad(ad_h)) {
            AppendableData::Priv(ref elt) => elt.encrypt_key,
            _ => ffi_try!(Err(FfiError::UnsupportedOperation)),
        };
        let handle = object_cache.insert_encrypt_key(pk);
        ptr::write(o_handle, handle);
        0
    })
}
................................................................................

/// Get number of appended data items.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_num_of_data(ad_h: AppendableDataHandle,
                                                     o_num: *mut usize)
                                                     -> i32 {
    helper::catch_unwind_i32(|| {
                                 ffi_try!(appendable_data_num_of_data_impl(ad_h, false, o_num));
                                 0
                             })
}

/// Get number of appended deleted data items.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_num_of_deleted_data(ad_h: AppendableDataHandle,
                                                             o_num: *mut usize)
                                                             -> i32 {
    helper::catch_unwind_i32(|| {
                                 ffi_try!(appendable_data_num_of_data_impl(ad_h, true, o_num));
                                 0
                             })
}

unsafe fn appendable_data_num_of_data_impl(ad_h: AppendableDataHandle,
                                           is_deleted_data: bool,
                                           o_num: *mut usize)
                                           -> Result<(), FfiError> {
    let mut object_cache = unwrap!(object_cache());
    let ad = object_cache.get_ad(ad_h)?;
    let num = match *ad {
        AppendableData::Pub(ref elt) => {
            if is_deleted_data {
                elt.deleted_data.len()
            } else {
                elt.data.len()
            }
................................................................................
        }
    };

    ptr::write(o_num, num);
    Ok(())
}

/// Get nth appended `DataIdentifier` from data.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_data_id(app: *const App,
                                                     ad_h: AppendableDataHandle,
                                                     n: usize,
                                                     o_handle: *mut DataIdHandle)
                                                     -> i32 {
    helper::catch_unwind_i32(|| {
                                 ffi_try!(appendable_data_nth_data_id_impl(app,
                                                                           ad_h,
                                                                           n,
                                                                           false,
                                                                           o_handle));
                                 0
                             })
}

/// Get nth appended `DataIdentifier` from deleted data.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_deleted_data_id(app: *const App,
                                                             ad_h: AppendableDataHandle,
                                                             n: usize,
                                                             o_handle: *mut DataIdHandle)
                                                             -> i32 {
    helper::catch_unwind_i32(|| {
                                 ffi_try!(appendable_data_nth_data_id_impl(app,
                                                                           ad_h,
                                                                           n,
                                                                           true,
                                                                           o_handle));
                                 0
                             })
}

unsafe fn appendable_data_nth_data_id_impl(app: *const App,
                                           ad_h: AppendableDataHandle,
                                           n: usize,
                                           is_deleted_data: bool,
                                           o_handle: *mut DataIdHandle)
                                           -> Result<(), FfiError> {
    let app = &*app;

    let mut object_cache = unwrap!(object_cache());

    let data_id = match *object_cache.get_ad(ad_h)? {
        AppendableData::Priv(ref elt) => {
            let priv_data = if is_deleted_data {
                nth(&elt.deleted_data, n)?
            } else {
                nth(&elt.data, n)?
            };
            let &(ref pk, ref sk) = app.asym_keys()?;
            priv_data
                .open(pk, sk)
                .map_err(CoreError::from)?
                .pointer

        }
        AppendableData::Pub(ref elt) => {
            if is_deleted_data {
                nth(&elt.deleted_data, n)?.pointer
            } else {
                nth(&elt.data, n)?.pointer
            }
        }
    };

    let handle = object_cache.insert_data_id(data_id);

    ptr::write(o_handle, handle);
................................................................................
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_data_sign_key(app: *const App,
                                                           ad_h: AppendableDataHandle,
                                                           n: usize,
                                                           o_handle: *mut SignKeyHandle)
                                                           -> i32 {
    helper::catch_unwind_i32(|| {
                                 ffi_try!(appendable_data_nth_sign_key_impl(app,
                                                                            ad_h,
                                                                            n,
                                                                            false,
                                                                            o_handle));
                                 0
                             })
}

/// Get nth sign key from deleted data
#[no_mangle]
pub unsafe extern "C" fn appendable_data_nth_deleted_data_sign_key(app: *const App,
                                                                   ad_h: AppendableDataHandle,
                                                                   n: usize,
                                                                   o_handle: *mut SignKeyHandle)
                                                                   -> i32 {
    helper::catch_unwind_i32(|| {
                                 ffi_try!(appendable_data_nth_sign_key_impl(app,
                                                                            ad_h,
                                                                            n,
                                                                            true,
                                                                            o_handle));
                                 0
                             })
}

unsafe fn appendable_data_nth_sign_key_impl(app: *const App,
                                            ad_h: AppendableDataHandle,
                                            n: usize,
                                            is_deleted_data: bool,
                                            o_handle: *mut SignKeyHandle)
                                            -> Result<(), FfiError> {
    let app = &*app;

    let mut object_cache = unwrap!(object_cache());

    let sign_key = match *object_cache.get_ad(ad_h)? {
        AppendableData::Priv(ref elt) => {
            let priv_data = if is_deleted_data {
                nth(&elt.deleted_data, n)?
            } else {
                nth(&elt.data, n)?
            };
            let &(ref pk, ref sk) = app.asym_keys()?;
            priv_data
                .open(pk, sk)
                .map_err(CoreError::from)?
                .sign_key

        }
        AppendableData::Pub(ref elt) => {
            if is_deleted_data {
                nth(&elt.deleted_data, n)?.sign_key
            } else {
                nth(&elt.data, n)?.sign_key
            }
        }
    };

    let handle = object_cache.insert_sign_key(sign_key);

    ptr::write(o_handle, handle);
................................................................................
            let data_id = *ffi_try!(object_cache.get_data_id(data_id_h));

            let client = unwrap!(client.lock());
            let sign_pk = ffi_try!(client.get_public_signing_key());
            let sign_sk = ffi_try!(client.get_secret_signing_key());

            let appended_data = ffi_try!(AppendedData::new(data_id, *sign_pk, sign_sk)
                                             .map_err(CoreError::from));

            match *ffi_try!(object_cache.get_ad(ad_h)) {
                AppendableData::Priv(ref elt) => {
                    let priv_appended_data = ffi_try!(PrivAppendedData::new(&appended_data,
                                                                            &elt.encrypt_key)
                                                              .map_err(CoreError::from));
                    ffi_try!(AppendWrapper::new_priv(elt.name,
                                                     priv_appended_data,
                                                     (sign_pk, sign_sk),
                                                     elt.version)
                                     .map_err(CoreError::from))
                }
                AppendableData::Pub(ref elt) => {
                    AppendWrapper::new_pub(elt.name, appended_data, elt.version)
                }
            }
        };

................................................................................
        let resp_getter = ffi_try!(unwrap!(client.lock()).append(append_wrapper, None));
        ffi_try!(resp_getter.get());

        0
    })
}

/// Get the current version of `AppendableData` by its handle
#[no_mangle]
pub unsafe extern "C" fn appendable_data_version(handle: AppendableDataHandle,
                                                 o_version: *mut u64)
                                                 -> i32 {
    helper::catch_unwind_i32(|| {
        *o_version = match *ffi_try!(unwrap!(object_cache()).get_ad(handle)) {
            AppendableData::Pub(ref mut elt) => elt.get_version(),
................................................................................
            AppendableData::Priv(ref mut elt) => elt.get_version(),
        };

        0
    })
}

/// See if `AppendableData` size is valid.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_validate_size(handle: AppendableDataHandle,
                                                       o_valid: *mut bool)
                                                       -> i32 {
    helper::catch_unwind_i32(|| {
        *o_valid = match *ffi_try!(unwrap!(object_cache()).get_ad(handle)) {
            AppendableData::Pub(ref elt) => elt.validate_size(),
................................................................................
            AppendableData::Priv(ref elt) => elt.validate_size(),
        };

        0
    })
}

/// Returns true if the app is one of the owners of the provided `AppendableData`.
#[no_mangle]
pub unsafe extern "C" fn appendable_data_is_owned(app: *const App,
                                                  handle: AppendableDataHandle,
                                                  o_is_owned: *mut bool)
                                                  -> i32 {
    helper::catch_unwind_i32(|| {
        let client = (*app).get_client();
................................................................................
            AppendableData::Priv(ref mut elt) => elt.get_owners().contains(&my_key),
        };

        0
    })
}

/// Free `AppendableData` handle
#[no_mangle]
pub extern "C" fn appendable_data_free(handle: AppendableDataHandle) -> i32 {
    helper::catch_unwind_i32(|| {
                                 let _ = ffi_try!(unwrap!(object_cache()).remove_ad(handle));
                                 0
                             })
}

// Convenience function to access n-th item from the given set, returning FfiError::InvalidIndex
// if not found.
fn nth<T>(items: &BTreeSet<T>, n: usize) -> Result<&T, FfiError> {
    items.iter().nth(n).ok_or(FfiError::InvalidIndex)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ffi::app::App;
    use ffi::errors::FfiError;
    use ffi::low_level_api::{AppendableDataHandle, DataIdHandle};
    use ffi::low_level_api::misc::*;
    use ffi::low_level_api::object_cache::object_cache;
    use ffi::test_utils;
    use rand;
    use routing::DataIdentifier;
    use rust_sodium::crypto::sign;
    use std::collections::HashSet;


    macro_rules! assert_num_of_data {
        ($ad_h:ident, $expected:expr) => {
            let mut num: usize = 0;
            assert_eq!(appendable_data_num_of_data($ad_h, &mut num), 0);
            assert_eq!(num, $expected);
        }
................................................................................

        unsafe {
            // Initialise public appendable data
            let mut ad_h = 0;
            assert_eq!(appendable_data_new_pub(&app, &rand::random(), &mut ad_h), 0);

            // Public appendable data doens't have a private owner key
            let err_code: i32 = FfiError::UnsupportedOperation.into();
            assert_eq!(appendable_data_encrypt_key(ad_h, &mut encrypt_key_h),

                       err_code);

            assert_eq!(appendable_data_free(ad_h), 0);

            // Initialise private appendable data
            let mut ad_h = 0;
            assert_eq!(appendable_data_new_priv(&app, &rand::random(), &mut ad_h),
                       0);
................................................................................

        (id, id_h)
    }

    fn get_sign_pk(app: &App) -> sign::PublicKey {
        let client = app.get_client();
        let client = unwrap!(client.lock());
        *unwrap!(client.get_public_signing_key())
    }

    fn reload_ad(app: &App, ad_id_h: DataIdHandle, ad_h: &mut AppendableDataHandle) {
        assert_eq!(appendable_data_free(*ad_h), 0);
        unsafe {
            assert_eq!(appendable_data_get(app, ad_id_h, ad_h), 0);
        }
    }
}