# Buggy code
def msb(a_sh):
    """
    Compute the most significant bit in a_sh, this is an implementation of the
    SecureNN paper https://eprint.iacr.org/2018/442.pdf

    Args:
        a_sh (AdditiveSharingTensor): the tensor of study
    Return:
        the most significant bit
    """

    alice, bob = a_sh.locations
    crypto_provider = a_sh.crypto_provider
    L = a_sh.field + 1  # field of a is L - 1
    dtype = get_dtype(L)
    input_shape = a_sh.shape
    a_sh = a_sh.view(-1)

    # the commented out numbers below correspond to the
    # line numbers in Table 5 of the SecureNN paper
    # https://eprint.iacr.org/2018/442.pdf

    # Common Randomness
    beta = _random_common_bit(alice, bob)
    u = _shares_of_zero(1, L, dtype, crypto_provider, alice, bob)

    # 1)
    x = torch.tensor(a_sh.shape).random_(get_max_val_field(L - 1))
    x_bit = decompose(x, L)
    x_sh = x.share(
        bob,
        alice,
        field=L - 1,
        dtype="custom",
        crypto_provider=crypto_provider,
        **no_wrap,
    )
    x_bit_0 = x_bit[..., 0]
    x_bit_sh_0 = x_bit_0.share(
        bob, alice, field=L, crypto_provider=crypto_provider, **no_wrap
    )
    x_bit_sh = x_bit.share(
        bob, alice, field=p, dtype="custom", crypto_provider=crypto_provider, **no_wrap
    )

    # 2)
    y_sh = a_sh * 2
    r_sh = y_sh + x_sh

    # 3)
    r = r_sh.reconstruct()  # convert an additive sharing in multi pointer Tensor
    r_0 = decompose(r, L)[..., 0]

    # 4)
    beta_prime = private_compare(x_bit_sh, r, beta, L)

    # 5)
    beta_prime_sh = beta_prime.share(
        bob, alice, field=L, dtype=dtype, crypto_provider=crypto_provider, **no_wrap
    )

    # 7)
    j = sy.MultiPointerTensor(
        children=[
            torch.tensor([0]).send(alice, **no_wrap),
            torch.tensor([1]).send(bob, **no_wrap),
        ]
    )
    gamma = beta_prime_sh + (j * beta) - (2 * beta * beta_prime_sh)

    # 8)
    delta = x_bit_sh_0 + (j * r_0) - (2 * r_0 * x_bit_sh_0)

    # 9)
    theta = gamma * delta

    # 10)
    a = gamma + delta - (theta * 2) + u

    if len(input_shape):
        return a.view(*list(input_shape))
    else:
        return a


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-902fb9b77716> in <module>
12 x = th.tensor([1.1,2.0,3.2,4.0]).fix_precision().share(*workers, crypto_provider=sw, requires_grad=True)
13 m=th.nn.Linear(4, 1).fix_precision().share(*workers, crypto_provider=sw, requires_grad=True)
---> 14 o=m(x)

/usr/local/lib/python3.7/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
491             result = self._slow_forward(*input, **kwargs)
492         else:
--> 493             result = self.forward(*input, **kwargs)
494         for hook in self._forward_hooks.values():
495             hook_result = hook(self, input, result)

/usr/local/lib/python3.7/site-packages/torch/nn/modules/linear.py in forward(self, input)
90     @weak_script_method
91     def forward(self, input):
---> 92         return F.linear(input, self.weight, self.bias)
93
94     def extra_repr(self):

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/hook/hook.py in overloaded_func(*args, **kwargs)
745                 handle_func_command = TorchTensor.handle_func_command
746
--> 747             response = handle_func_command(command)
748
749             return response

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/tensors/interpreters/native.py in handle_func_command(cls, command)
310             new_command = (cmd, None, new_args, new_kwargs)
311             # Send it to the appropriate class and get the response
--> 312             response = new_type.handle_func_command(new_command)
313             # Put back the wrappers where needed
314             response = syft.frameworks.torch.hook_args.hook_response(

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/tensors/interpreters/autograd.py in handle_func_command(cls, command)
236             # Try to get recursively the attributes in cmd = "<attr1>.<attr2>.<attr3>..."
237             cmd = cls.rgetattr(cls, cmd)
--> 238             return cmd(*args, **kwargs)
239         except AttributeError:
240             pass

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/tensors/interpreters/autograd.py in linear(*args)
201                     Un-hook the function to have its detailed behaviour
202                     """
--> 203                     return torch.nn.functional.native_linear(*args)
204
205                 module.linear = linear

/usr/local/lib/python3.7/site-packages/torch/nn/functional.py in linear(input, weight, bias)
1406         ret = torch.addmm(bias, input, weight.t())
1407     else:
-> 1408         output = input.matmul(weight.t())
1409         if bias is not None:
1410             output += bias

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/tensors/interpreters/autograd.py in method_with_grad(*args, **kwargs)
138                 )
139
--> 140                 result = getattr(new_self, name)(*new_args, **new_kwargs)
141
142                 # Put back SyftTensor on the tensors found in the response

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/tensors/interpreters/precision.py in matmul(self, *args, **kwargs)
414
415         # Send it to the appropriate class and get the response
--> 416         response = getattr(new_self, "matmul")(*new_args, **new_kwargs)
417
418         # Put back SyftTensor on the tensors found in the response

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/tensors/interpreters/additive_shared.py in matmul(self, other)
515             return self._public_mul(other, "matmul")
516
--> 517         return self._private_mul(other, "matmul")
518
519     def mm(self, *args, **kwargs):

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/tensors/interpreters/additive_shared.py in _private_mul(self, other, equation)
413             raise AttributeError("For multiplication a crypto_provider must be passed.")
414
--> 415         shares = spdz.spdz_mul(cmd, self, other, self.crypto_provider, self.field)
416
417         return shares

/usr/local/lib/python3.7/site-packages/syft/frameworks/torch/crypto/spdz.py in spdz_mul(cmd, x_sh, y_sh, crypto_provider, field)
43         j = sy.MultiPointerTensor(children=[j1, j0])
44     else:
---> 45         j = sy.MultiPointerTensor(children=[j1] + j0.child.values())
46
47     delta_b = cmd(delta, b)

TypeError: can only concatenate list (not "dict_values") to list

# Fixed code
def msb(a_sh):
    """
    Compute the most significant bit in a_sh, this is an implementation of the
    SecureNN paper https://eprint.iacr.org/2018/442.pdf

    Args:
        a_sh (AdditiveSharingTensor): the tensor of study
    Return:
        the most significant bit
    """

    workers = a_sh.locations
    crypto_provider = a_sh.crypto_provider
    L = a_sh.field + 1  # field of a is L - 1
    dtype = get_dtype(L)
    input_shape = a_sh.shape
    a_sh = a_sh.view(-1)

    # the commented out numbers below correspond to the
    # line numbers in Table 5 of the SecureNN paper
    # https://eprint.iacr.org/2018/442.pdf

    # Common Randomness
    beta = _random_common_bit(*workers)
    u = _shares_of_zero(1, L, dtype, crypto_provider, *workers)

    # 1)
    x = torch.tensor(a_sh.shape).random_(get_max_val_field(L - 1))
    x_bit = decompose(x, L)
    x_sh = x.share(
        *workers,
        field=L - 1,
        dtype="custom",
        crypto_provider=crypto_provider,
        **no_wrap,
    )
    x_bit_0 = x_bit[..., 0]
    x_bit_sh_0 = x_bit_0.share(
        *workers, field=L, crypto_provider=crypto_provider, **no_wrap
    )
    x_bit_sh = x_bit.share(
        *workers, field=p, dtype="custom", crypto_provider=crypto_provider, **no_wrap
    )

    # 2)
    y_sh = a_sh * 2
    r_sh = y_sh + x_sh

    # 3)
    r = r_sh.reconstruct()  # convert an additive sharing in multi pointer Tensor
    r_0 = decompose(r, L)[..., 0]

    # 4)
    beta_prime = private_compare(x_bit_sh, r, beta, L)

    # 5)
    beta_prime_sh = beta_prime.share(
        *workers, field=L, dtype=dtype, crypto_provider=crypto_provider, **no_wrap
    )

    # 7)
    j = sy.MultiPointerTensor(
        children=[
            torch.tensor([int(i == 0)]).send(w, **no_wrap)
            for i, w in enumerate(workers)
        ]
    )
    gamma = beta_prime_sh + (j * beta) - (2 * beta * beta_prime_sh)

    # 8)
    delta = x_bit_sh_0 + (j * r_0) - (2 * r_0 * x_bit_sh_0)

    # 9)
    theta = gamma * delta

    # 10)
    a = gamma + delta - (theta * 2) + u

    if len(input_shape):
        return a.view(*list(input_shape))
    else:
        return a