mod.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. use na::{DMatrix, DVector};
  2. use pairing::{PrimeField, Field};
  3. use pairing::bls12_381::{Fq, FqRepr};
  4. pub fn u64_to_field<F: PrimeField>(x: u64) -> F {
  5. F::from_repr(
  6. <F::Repr as From<u64>>::from(x)
  7. ).unwrap()
  8. }
  9. #[derive(Debug, Clone, PartialEq)]
  10. pub enum Gate<'a> {
  11. Attribute(&'a [u8]),
  12. Threshold {t: usize, children: Vec<Gate<'a>>},
  13. }
  14. impl<'a> Gate<'a> {
  15. fn children(self) -> Vec<Gate<'a>> {
  16. match self {
  17. Gate::Threshold {children, ..} => children,
  18. Gate::Attribute (_) => Vec::new(),
  19. }
  20. }
  21. fn label(self) -> &'a [u8] {
  22. match self {
  23. Gate::Threshold {..} => b"",
  24. Gate::Attribute (l) => l,
  25. }
  26. }
  27. fn lsss(&self) -> DMatrix<u64> {
  28. match self {
  29. &Gate::Attribute (_) => DMatrix::from_row_slice(1, 1, &[1u64]),
  30. &Gate::Threshold {t, ref children} => {
  31. let m = children.len();
  32. DMatrix::from_fn(m, t, |i, j| {
  33. ((i as u64) + 1).pow(j as u32)
  34. })
  35. }
  36. }
  37. }
  38. fn rec_msp(ast: AS<'a>) -> AS<'a>{
  39. // find the first threshold-tree string rather than a simple attribute
  40. let at = ast.rho.iter().enumerate().skip_while(|&(_, g)| {
  41. match *g {
  42. Gate::Attribute (_) => true,
  43. Gate::Threshold {..} => false,
  44. }
  45. }).next();
  46. // if none is found, simply return ast, we're done.
  47. // otherwise, [cont.]
  48. if let Some((i, g)) = at {
  49. let mg = g.lsss();
  50. // refresh rho with the resolved attribute
  51. let mut rho = ast.rho.clone();
  52. rho.remove(i);
  53. // XXX. lots of cloning for the safety god.
  54. // perhaps the fact that we're inside a class can spare us
  55. // the copy of all the gates?
  56. for c in g.clone().children().iter() {
  57. rho.insert(i, c.clone());
  58. }
  59. let (m1, d1) = ast.m.shape();
  60. let (m2, d2) = mg.shape();
  61. // insert the lsss matrix into m
  62. let w = ast.m.row(i).kronecker(&mg.column(0));
  63. let mg = mg.remove_column(0);
  64. let m = ast.m.remove_row(i);
  65. let m = DMatrix::from_fn(
  66. m1 + m2 - 1,
  67. d1 + d2 - 1,
  68. |row, col| {
  69. if row < i && col < d1 { m[(row, col)] }
  70. else if row < i && col >= d1 { 0 }
  71. else if row < i+m2 && col < d1 { w[(row-i, col)] }
  72. else if row < i+m2 && col >= d1 { mg[(row-i, col-d1)] }
  73. else if row >= i+m2 && col < d1 { m[(row-m2, col)] }
  74. else { 0 }
  75. }
  76. );
  77. Self::rec_msp(AS {m, rho})
  78. } else {
  79. ast.clone()
  80. }
  81. }
  82. fn msp(self) -> AS<'a> {
  83. let rho = vec![self];
  84. let m = DMatrix::from_row_slice(1, 1, &[1u64]);
  85. let ast = Self::rec_msp(AS {m, rho});
  86. ast
  87. }
  88. }
  89. #[derive(Clone)]
  90. struct AS<'a> {
  91. m: DMatrix<u64>,
  92. rho: Vec<Gate<'a>>,
  93. }
  94. impl<'a> AS<'a> {
  95. fn gen_shares<F: PrimeField>(&self) -> DVector<F> {
  96. let m = DMatrix::<F>::from_fn(self.m.nrows(), self.m.ncols(),
  97. |row, col| { u64_to_field(self.m[(row, col)]) }
  98. );
  99. DVector::from_fn(self.m.nrows(),
  100. |row, col| { F::one() }
  101. )
  102. }
  103. }
  104. mod tc {
  105. use std::str;
  106. use std::str::FromStr;
  107. use nom::{digit, alphanumeric};
  108. use msp::Gate;
  109. named!(parens <Gate>, ws!(delimited!(tag!("("), threshold_gate, tag!(")") )) );
  110. named!(threshold_gate <Gate>,
  111. do_parse!(
  112. t: threshold >>
  113. children: attributes >>
  114. (Gate::Threshold {t, children})
  115. )
  116. );
  117. named!(attributes < Vec<Gate<'a>> >,
  118. many1!(preceded!(tag!(","), parse))
  119. );
  120. named!(threshold <usize>,
  121. map_res!(map_res!(ws!(digit), str::from_utf8),
  122. FromStr::from_str)
  123. );
  124. named!(attribute <Gate>,
  125. map!(ws!(alphanumeric), Gate::Attribute)
  126. );
  127. named!(pub parse <Gate>,
  128. alt!(attribute | parens)
  129. );
  130. }
  131. mod bc {
  132. use nom::{IResult, alphanumeric};
  133. use msp::Gate;
  134. named!(parens<Gate>, ws!(delimited!( tag!("("), expr, tag!(")") )) );
  135. named!(attribute <Gate>,
  136. map!(ws!(alphanumeric), Gate::Attribute)
  137. );
  138. named!(gate <Gate>,
  139. alt!(attribute | parens)
  140. );
  141. named!(term <Gate<'a>>,
  142. do_parse!(
  143. init: gate >>
  144. res: fold_many0!(
  145. pair!(alt!(tag!("^") | tag!("∧") | tag!("and")), gate),
  146. init,
  147. |acc, (op, g): (&[u8], Gate<'a>)| {
  148. let v: Vec<Gate<'a>> = vec![acc, g];
  149. Gate::Threshold {t: 2usize, children: v}
  150. }
  151. ) >>
  152. (res)
  153. )
  154. );
  155. named!(expr <Gate<'a>>,
  156. do_parse!(
  157. init: term >>
  158. res: fold_many0!(
  159. pair!(alt!(tag!("v") | tag!("or") | tag!("∨")), term),
  160. init,
  161. |acc, (op, g): (&[u8], Gate<'a>)| {
  162. let v: Vec<Gate<'a>> = vec![acc, g];
  163. Gate::Threshold {t: 2usize, children: v}
  164. }
  165. ) >>
  166. (res)
  167. )
  168. );
  169. // XXX. this needs to be changed into a result type.
  170. // Also note that making instead "expr" pub will fuck up everything
  171. // because the "lifetime is not defined" - not sure I really understood why.
  172. pub fn parse(i: &[u8]) -> IResult<&[u8], Gate, u32> {
  173. expr(i)
  174. }
  175. }
  176. #[test]
  177. fn test_tc_parse() {
  178. // see eprint 2010/374
  179. let policy = b"(2, (2, (3, I, J, K, L), G, H), (2, A, B, C), (2, D, E, F))";
  180. let (_, pp) = tc::parse(policy).unwrap();
  181. let msp = pp.msp();
  182. assert_eq!(msp.rho.len(), 12);
  183. let expected = DMatrix::from_row_slice(12, 2 + (2-1) + (3-1) + (2-1) + (2-1),
  184. &[1, 1, 1, 0, 0, 0, 0,
  185. 1, 1, 2, 0, 0, 0, 0,
  186. 1, 1, 3, 0, 0, 0, 0,
  187. 1, 2, 0, 1, 0, 0, 0,
  188. 1, 2, 0, 2, 0, 0, 0,
  189. 1, 2, 0, 3, 0, 0, 0,
  190. 1, 3, 0, 0, 1, 0, 0,
  191. 1, 3, 0, 0, 2, 0, 0,
  192. 1, 3, 0, 0, 3, 1, 1,
  193. 1, 3, 0, 0, 3, 2, 4,
  194. 1, 3, 0, 0, 3, 3, 9,
  195. 1, 3, 0, 0, 3, 4, 16,
  196. ]
  197. );
  198. assert_eq!(expected, msp.m)
  199. }
  200. use std::collections::VecDeque;
  201. pub struct Bfs<'a> {
  202. stack: VecDeque<Gate<'a>>
  203. }
  204. impl<'a> Bfs<'a> {
  205. fn new(g: Gate<'a>) -> Self {
  206. let mut stack = VecDeque::new();
  207. stack.push_back(g);
  208. Bfs { stack }
  209. }
  210. }
  211. impl<'a> Iterator for Bfs<'a> {
  212. type Item = Gate<'a>;
  213. fn next(&mut self) -> Option<Self::Item> {
  214. let g = self.stack.pop_front()?;
  215. let children = g.clone().children();
  216. self.stack.extend(children.iter().cloned());
  217. Some(g)
  218. }
  219. }
  220. #[test]
  221. fn test_bc_parse() {
  222. let policy = b"intern and topsecret or xkeyscore";
  223. let (_, gate) = bc::parse(policy).unwrap();
  224. let children = gate.children();
  225. assert_eq!(children.len(), 2);
  226. }
  227. #[test]
  228. fn test_bfs() {
  229. let policy = b"1 and (3 and 4)";
  230. let (_, gate) = bc::parse(policy).unwrap();
  231. assert_eq!(gate.clone().children().len(), 2);
  232. let mut bfs = Bfs::new(gate);
  233. let root = bfs.next();
  234. let expected = Gate::Attribute(b"1");
  235. assert_eq!(Some(expected), bfs.next());
  236. assert_eq!(bfs.next().unwrap().children().len(), 2);
  237. }
  238. #[test]
  239. fn test_matrix_field() {
  240. let policy = b"1 and 2";
  241. let (_, gate) = bc::parse(policy).unwrap();
  242. let msp = gate.msp();
  243. let m = msp.m;
  244. let mm = DVector::<Fq>::from_fn(m.ncols(),
  245. |row, col| {
  246. u64_to_field(m[(row, col)])
  247. }
  248. );
  249. let v = DVector::from_fn(m.ncols(), |row, col| { 1u64 });
  250. let vv = DVector::from_fn(m.ncols(), |row, col| { Fq::one() });
  251. let d = mm.dot(&vv);
  252. }