Detailed introduction of matrix element security multi-party

detailed introduction matrix element security


 

Chapter one MPC&JUGO

1. summary

Big data era , Cross computing of massive data can be used for scientific research 、 Medical care 、 Finance and so on to provide better support . Many enterprises or organizations consider information security or interests , Internal data is not open . Form a data island , The value of the data cannot be reflected or realized . secure multi-party computation (MPC) It can solve this problem very well . While ensuring the data security of all parties , And get the expected results .

In order to make data collide more value safely , Breaking data in the industry 、 Barriers to inter firm mobility , Matrix elements are introduced JUGO Secure multiparty computing platform .JUGO Provide a secure multi-party computing platform , And integrated with general MPC Algorithm SDK. At the same time, it provides writing high-level language Frutta Of IDE, For the convenience of users Frutta A program written in language is converted into a circuit . Users can write... On the platform MPC Algorithm and release , You can also initiate calculation tasks , Invite a third party to perform secure multi-party computing or apply to participate in computing tasks initiated by others .

Users deploy computing nodes locally , You can choose JUGO Open service platform as agent ( It can also be a third party ), The nodes communicate with each other by proxy , All nodes do not retain any data . There is no clear text or original data spread or exist in the whole calculation process , Finally, the calculation result is sent to the receiver agreed in advance .

JUGO Open service platform is a data processing factory , It's also an algorithm and data mart . On the premise of protecting data security, help the seller to add value to user data 、 Cash in , Help buyer users find the data and services they need .

For the flow of data is the slogan and vision of matrix elements , Mobile data is more valuable .

JUGO characteristic :

  • Support semi-honest General two party algorithm :GC+OT.
  • Support Frutta Compiling IDE, Provide MPC Algorithm SDK, The user to use IDE and SDK Development .
  • Support addition (addition), Compare (comparison) Multiparty algorithm .
  • Later support general multi-party algorithm and hardware acceleration

2.MPC A term is used to explain

name Full name Chinese name explain
MPC Secure Multi-Party Computation secure multi-party computation A multi-party computing algorithm to protect data security and privacy .
GC Garbled Circuit Encryption circuit A way of processing circuits by encryption .
OT: Oblivious Transfer Inadvertently transmit A safe choice 、 Transfer protocol .

One 、MPC Introduce

1. The value of secure multiparty Computing

MPC Is an important branch of cryptography , The purpose of this paper is to solve the problem of privacy preserving collaborative computing among a group of participants who do not trust each other , To provide the data demander with the ability of multi-party collaborative computing without disclosing the original data .

In the current environment where personal data has no privacy , It is very important to confirm the right of data and realize the value of data .MPC It's the computing protocol that does this , In the whole process of computing protocol execution , Users always have control over personal data , Only computational logic is open . Calculation participants only need to participate in the calculation agreement , No need to rely on a third party to complete the data calculation , And the participants can not infer the original data after getting the calculation results .

2. The source of secure multiparty Computing

secure multi-party computation (MPC:Secure Muti-Party Computation) Research by Turing Prize Winners 、 Professor Yao Jizhi, academician of the Chinese Academy of Sciences, is in 1982 in , Professor Yao explains secure multiparty computing with the famous millionaire problem . The millionaire problem means , Without a trusted third party , How do two millionaires not reveal their real wealth to compare who is richer . By studying this question , It vividly illustrates the challenges and solutions of secure multiparty computing , the Oded Goldreich、Shaft Goldwasser Many original innovative works of scholars , Secure multi-party computing has become an important branch of cryptography .

3. The problem is abstract

Secure multiparty computing can be understood as : Each party has its own private data , Without divulging their own private data , Be able to work out about common functions Result . When the whole calculation is finished , Only the calculation results are known to both parties , And both parties do not know the data of the other party and the intermediate data of the calculation process .

4. What is secure multiparty computing ?

Multiple parties holding their own private data , Perform a calculation logic together ( Such as , Calculate the maximum value ), And get the calculation result . But in the process , Each party involved will not disclose the calculation of its own data , It's called MPC Calculation .

for instance ,Bob and Alice Want to find out who's paid more , However, due to the signing of the confidentiality agreement, the specific salary cannot be disclosed . If Bob and Alice Tell the former employees their salaries respectively Anne, At this time Anne You know who's paid more , And tell Bob and Alice. This way is to ensure that the middleman Anne Completely believable .

And by MPC You can design a protocol , In this Agreement , Algorithm replaces the role of middleman ,Alice and Bob The salary of and the logic of comparison are handled by the algorithm , The participants only need to execute the calculation agreement , Instead of relying on a fully trusted third party .

The basic nature of secure multiparty computing is : The private data information held by each party cannot be inferred from the messages sent during the execution of the agreement , The only information that can be inferred about private data is information that can only be obtained from the output results .

4.1. What is algorithm

Algorithm (Algorithm) It refers to the accurate and complete description of the solution , It's a series of clear instructions to solve problems , Algorithms represent a systematic approach to describe the policy mechanisms for solving problems . in other words , Be able to input certain specifications , Obtain the required output in a limited time .

If an algorithm is defective , Or not suitable for a problem , Executing this algorithm will not solve this problem . Different algorithms may take different time 、 Space or efficiency to accomplish the same task . The advantages and disadvantages of an algorithm can be measured by the complexity of space and time .

The algorithm has the following five important features :

  • Fineness : The finiteness of the algorithm means that the algorithm must be able to terminate after a limited number of steps ;
  • Accuracy : Every step of the algorithm must be defined exactly ;
  • Input item : An algorithm has 0 One or more inputs , To describe the initial situation of the operation object , So-called 0 An input is when the algorithm itself sets the initial conditions ;
  • Output item : An algorithm has one or more outputs , To reflect the result of processing the input data . Algorithms without output make no sense ;
  • The feasibility of : Any calculation step in the algorithm can be decomposed into basic executable operation steps , That is, each calculation step can be completed in a limited time ( It's also called validity ).

Be careful : As mentioned in the document “ Algorithm ”, especially MPC Bottom algorithm ;“ Calculation logic ” In particular, algorithms written to perform specific operations , Running on the MPC Above the underlying algorithm .

4.2.MPC Problem classification

  • From the applicability of the algorithm ,MPC It is applicable to specific algorithms , Such as addition 、 Multiplication 、AES, Assemble, intersect, etc ; It is also applicable to all general algorithms that can be expressed as calculation process .

  • The number of participants varies according to the calculation , It can be divided into two parties 2PC And multiple parties (≥3) Common to MPC.

  • The protocol used for secure two party computing is Garbled Circuit(GC)+Oblivious Transfer(OT); The protocol used in secure multiparty computing is homomorphic encryption + Secret sharing +OT.

  • In secure multiparty Computing , Security challenge model includes semi honest adversary model and malicious adversary model . Most of the market scenarios satisfy the semi honest adversary model , It's also JUGO The adversary model considered by technical products .

  • Semi honest adversary model : There is a need for the computing party to obtain the original data of other computing parties , But still in accordance with the calculation agreement . A semi honest relationship means that there is a certain trust relationship between participants , Suitable for data calculation between agencies ;

  • Malicious adversary model : The participants do not perform the calculation process according to the calculation agreement at all . Participants may use any ( malice ) Way to communicate with each other , And there's no trust . The result may be that the implementation of the agreement is not successful , There's no data for both sides ; Or the agreement is executed successfully , Both parties only know the calculation result . More for individuals 、 Or between individuals and institutions .

5.MPC Basic principle of algorithm (2PC Semi honest model )

The following describes the semi honest model of secure two-party computing MPC Algorithm principle :

5.1.MPC Algorithm execution process

  • First, preprocess the input data .

Follow the principles :1、 As little data input as possible ;2、 As much data preprocessing as possible

—— When the amount of data is too large, the efficiency of algorithm execution will be greatly reduced .

  • The computational logic is transformed into a Boolean circuit .

Follow the principles : Try to be as simple as possible

—— because MPC It's computation intensive and communication intensive algorithms , If the computational logic is complex , It will have a great impact on the efficiency of execution .

The way of transformation : Manual / Circuit compiler Frutta

  • Make the input Boolean circuit GC and OT Algorithm ( The details are described below ), Get the output .

5.2.GC+OT The basic framework of two-way calculation

GC+ OT It's on both sides semi-honest The general algorithm under the model , That is to say, it can support the safe two-way calculation of any computing logic .

The general framework is shown below :

6. Summary

Secure multiparty computing is a kind of computing without leaking the original data , Calculation of data . The above content first introduces MPC Value and source of , Then, the principle of technical implementation of two-way secure computing is described in detail , It mainly includes GC and OT Algorithm , It also gives a brief overview of some basic technical knowledge .

Two 、JUGO And MPC

1.JUGO location

For enterprise users , be based on MPC Security data trading platform . By deploying... Locally MPC node , Data co Computing .

2.JUGO characteristic

  • Support semi-honest General two party algorithm :GC+OT.

  • Support Frutta Compiling IDE, Provide MPC Algorithm SDK, The user to use IDE and SDK Development .

  • Support addition (addition), Compare (compare) And so on .

  • Provided in the form of browser plug-ins MPC Personal experience .

  • Later support general multi-party algorithm and hardware acceleration .

3.JUGO framework

For computing logic providers ,MPC-IDE Realize the compilation of calculation logic , And through the integrated circuit compiler into circuit files ; As data executor , Matrix elements provide MPC-SDK Directly serve the computing logic provider ; And matrix element pairs MPC-SDK Internal algorithm implementation GPU、FPGA Wait for hardware acceleration , Make collaborative computing faster .

3、 ... and 、MPC Application scenarios

1.MPC Applicable scenario

1.1. Data security query

Government departments often store a large number of data on the operation of citizens and enterprises in their systems , Many business organizations need to query information for business purposes , But the government doesn't want the data to be leaked or copied , meanwhile , In some cases, commercial organizations do not want the government to know their query conditions . Using secure multiparty Computing , Can realize data security query .

Data security query solution can also be applied in business competition 、 Data cooperation and many other fields .

1.2. Joint data analysis

Cross agency cooperation and operation of multinational companies often need to obtain data from multiple data sources , Put together a whole amount of data and analyze , Existing data analysis algorithms may lead to privacy exposure and data ownership transfer , The application of secure multi-party computing technology can enable the original data to be calculated without collection and sharing , Protect the privacy and asset security of the target data holder .

2.MPC Range of application

Whether it's resources flowing around the world 、 goods 、 capital 、 technology 、 people 、 Data or ideas , Or conflicts caused by various real world frictions 、 Supervision and restriction, etc , It's affecting the economy 、 Culture 、 education 、 Medical care 、 Judgment and use of information in all walks of life, such as public management .

Data flow and collaborative analysis are of great value in all industries , It also generates a lot of application requirements :

1、 The financial sector

Finance itself is a business risk industry , Risk control and credit investigation are important means for financial industry to manage risks . The problem of traditional data analysis model is , Data collection scope is limited 、 Platform upload data enthusiasm is low 、 Update not in time 、 High access threshold . and MPC The local data collection mode supported by credit reporting mode , Make up for the old traditional credit data 、 The defect of lagging risk assessment , It can support the collaborative computing with diversified data types , The scope of data analysis from financial credit data , Expand to medical 、 insurance 、 In the credit evaluation system of transportation and other industries , Get a broader picture of social credit evaluation .

2、 manufacturing

The digital transformation of manufacturing industry has brought more precision to all kinds of manufacturing enterprises 、 More advanced technology , And better products . And supply data to the industry as a whole 、 Frequency of production 、 Comprehensive analysis of maintenance situation, etc , It can provide strong data support for cost reduction and efficiency improvement of the industry , Reduce the pain of overcapacity . Characteristics of global distribution of manufacturing industry , And relatively low level of information technology application in the financial industry , There is a certain resistance to the flow and sharing of data .MPC The use of technology in manufacturing , Data interoperability can be removed from the limits of national borders , Provide guarantee for global manufacturing supply chain optimization ; Through in-depth mining and multi maintenance analysis of the industry's overall data or market demand , Global production system can be configured accurately , More flexible arrangements for the launch of products in various markets , Keep abreast of the industry trend .

3、 Medical industry

The sensitivity of medical data makes medical institutions 、 insurance 、 Pharmaceutical enterprises 、 It is difficult to achieve low cost among medical equipment suppliers 、 Efficient medical information data exchange and sharing , Thus, a large number of data resources in the industry have not been effectively used and in-depth analysis .MPC The application of technology in the medical industry , Can be between relatively closed medical data participants , Set up a safe and reliable data exchange network , Maximize the value of medical data .

Chapter two API Tutorial

1. programing language & development environment

1.1. Computational logic programming language

Frutta Language

1.2.IDE development environment

operating system windows( Follow up support linux),chrome browser ( It needs to be installed first Frutta Google browser plugin )

1.3.MPC Application deployment

Environment building ( requirement linux System )

install nginx

install JDK, To configure JDK environment variable

2. Installing a plug-in

Use JUGO-IDE Before , You need to install Frutta Google browser plugin . After installation can be in JUGO-IDE Use in Frutta Language programming algorithm .

Installation steps :

First step , Please click download Frutta Google browser plug-in installation package , And decompress it locally .

The second step , stay Chrome Browser address bar input chrome://extensions/, Enable Developer mode , Then click the button “ Load the unzipped extender ”, Select the folder where the plug-in is located .

Be careful : Because the plug-in has not been uploaded yet Google Plug in store , So it can only run in developer mode . open chrome://extensions/, Open the developer mode as shown below . Because it runs the plug-in in developer mode ,Chrome The browser will pop up “ Please disable the extensions running in developer mode ” A hint of , Click here “ Cancel ” To continue to use Frutta Google browser plugin .

3.JUGO-IDE

JUGO-IDE yes JUGO Technical products are provided for developers to write MPC Algorithm development tools .

combination Frutta Google browser plugin , Developers can write quickly without building any environment 、 compile 、 Running and publishing algorithms .

By using JUGO-IDE, Developers can use Frutta Language programming algorithm , And pass JUGO-IDE It can be compiled in JUGO Circuit files and... Executed on technical products java Template file . details

4.Frutta Language

Frutta Matrix element is a special programming language for the generation of algorithm circuit files for secure multiparty computing . It's a kind of high-level language , It's also a process oriented programming language .Frutta Supports most operators 、 data type , The expression is flexible and practical . Currently only matrix elements are available online ide You can compile and run .ide You can put Frutta The file can be compiled in JUGO Circuit files executed on the platform . details

5. Development programming

5.1. Computational logic programming

Calculation logic : The algorithm for the realization of secure multi-party computing in a certain scenario .

Use Frutta Language , stay JUGO-IDE Can quickly complete the calculation of logic programming 、 Validation and release .

5.2.JUGO-SDK

JUGO-SDK yes JUGO Technology products for developers to provide a secure multi-party computing application development kit .

Developers use JUGO-SDK And others JUGO Technical products , It can be developed efficiently and quickly MPC( secure multi-party computation ) application . Each integrates SDK The application will be connected to the computing network as a computing node . Application call SDK Secure multi-party computing can be implemented to meet business needs .

Integration process :

  1. IDE Write circuit algorithm on ;
  2. Compile algorithms and generate circuit files JAVA Packaging ; Sample view
  3. Introduce steps... Into the project 2 Medium JAVA Packaging ;
  4. Integrate API, Complete application development ;

5.3. Application deployment

The application contains three parts of code . Include :1) Algorithm code 、2) Server application code 、3) The front page shows the code .

Implementation process :

1) MPC Application deployment

preparation :

Environment building ( requirement linux System )

install nginx

install JDK, To configure JDK environment variable

2) Project package

describe :

Project dependence gradle Build ;

It can be done by gradle The instructions are packed , The file output is at the same level build Under the table of contents ;

It can be done by JAVA IDE Package executables ;

gradle Instructions :

>clean build
Copy

3) Project operation

describe :

Execute the following instructions in the environment to monitor ;

The statistical catalogue can be used later nohup.out Check the output log

Instruction reference :

>nohup java -jar MPCAcceptApp.jar &// Start the receiver node
>nohup java -jar MPCStartApp.jar &// Start initiator node
Copy

4) Project commissioning

Deployment complete .

Enter... In the browser

http://ip:port/swagger-ui.html , Can debug initiator interface .

Enter... In the browser

http://ip:port/swagger-ui.html , Debuggable receiver interface . details

The third chapter Frutta Language

1. What is? Frutta

Frutta Matrix element is a special programming language for the generation of algorithm circuit files for secure multiparty computing . It's a kind of high-level language , It's also a process oriented programming language .Frutta Supports most operators 、 data type , The expression is flexible and practical . Currently only matrix elements are available online ide You can compile and run .ide You can put Frutta The file can be compiled in JUGO Circuit files executed on the platform .

2. Program structure

Before we learn Frutta Before the basic building blocks of language , Let's take a look at the smallest Frutta Program structure , It can be used as a reference in the following chapters .

Frutta The language mainly includes the following parts :

  • Preprocessor instruction
  • I / O definition
  • function
  • Variable
  • sentence & expression
  • notes
1. #parties 2 /* Two participants */
2.
3. #input 1 int32 /* Participant 1, It can be a basic type , It can also be an array , Complex types such as structures */
4. #input 2 int32 /* Participant 2 */
5. #output 1 int32 /* The exporter */
6.
7. /* The main function , Complete the addition operation */
8. function void main()
9. {
10. output1 = input1 + input2;
11. }

One 、 Basic grammar

Frutta The program consists of a variety of Token form ,Token It can be a keyword 、 identifier 、 Constant 、 A string value , Or a symbol .

  • A semicolon

stay Frutta In the program , Semicolons are statement terminators . in other words , Each statement must end with a semicolon . It shows the end of a logical entity .

  • notes

Comments are like help text in a program , They are ignored by the compiler . They use /* Start , In characters */ End .

You cannot embed comments in comments , Comments cannot also appear in strings or character values .

  • identifier

Identifiers are used to identify variables 、 function , Or any other user-defined project name . An identifier is in letters A-Z or a-z Or the underscore _ Start , Followed by zero or more letters 、 Underline and numbers (0-9).

Punctuation characters... Are not allowed in identifiers , such as @、$ and %. Identifiers are case sensitive . therefore ,Manpower and manpower Are two different identifiers . A few valid identifiers are listed below :

 mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal
Copy
  • keyword

The following table lists them Frutta Reserved word in . These reserved words cannot be used as constant names 、 Variable name or other identifier name . For input and output , Please follow the order , Write in turn . The number of inputs is consistent with the number of participants in the calculation . Such as the 3 Number of calculation squares , Then define in turn input 1 xxx, input 2 xxx, input 3 xxx. The output is the same .

else typedef return for void if struct abs max min
int8 uint8 int16 uint16 int32 uint32 int64 uint64 bool
input1 input2 ... inputN output1 output2 ... outputN
Copy
  • Space

Lines that contain only spaces , It's called a blank line , Maybe with comments , The compiler will completely ignore it .

stay Frutta in , Spaces are used to describe spaces 、 tabs 、 Line breaks and comments . Spaces separate parts of a statement , Let the compiler recognize an element in a statement ( such as int) Where to end , Where does the next element start . therefore , In the following sentence :type age;. ad locum ,type and age There must be at least one space character between ( It's usually a blank character ), So that the compiler can distinguish them . On the other hand , In the following sentence :

fruit = apples + oranges;
Copy

fruit and =, perhaps = and apples The space character between is not required , But to enhance readability , You can add some spaces as needed .

Two 、 The preprocessor

The preprocessor is not part of the compiler , But it's a separate step in the compilation process . in short , Preprocessor is just a text replacement tool , They instruct the compiler to complete the required preprocessing before the actual compilation .

All preprocessor commands are signed with a pound sign (#) start . It must be the first non empty character , To enhance readability , Preprocessor instructions should start with the first column .

stay Frutta in , Two types of precompiler instructions are supported :

  • include

Support to include external files , External files support the following types of external files :

  • Frutta file

Use Frutta Implementation files , The functions implemented in can be called in the current file . Be careful , Only the current file , Non current directory is not supported , For example, it doesn't support #include "./lib/math.wir", Only support #include "math.wir". A complete example is as follows :

1. // math.wir
2. function int32 add(int32 x, int32 y)
3. {
4. return x + y;
5. }
6.
7. function int32 sub(int32 x, int32 y)
8. {
9. return x - y;
10. }
11.
12. function int32 mul(int32 x, int32 y)
13. {
14. return x * y;
15. }
16.
17. function int32 div(int32 x, int32 y)
18. {
19. return x / y;
20. }
21.
22. typedef struct Point
23. {
24. int32 x;
25. int32 y;
26. }
27.
28. /* Find the distance between two points */
29. function int32 dis(Point p1, Point p2)
30. {
31. int32 x = sub(p1.x, p2.x);
32. int32 y = sub(p1.y, p2.y);
33.
34. return add(mul(x, x), mul(y, y));
35. }
36.
37. // include.wir
38. #include "math.wir"
39.
40. #parties 2
41. #input 1 Point
42. #input 2 Point
43. #output 1 int32
44.
45. function void main()
46. {
47. output1 = dis(input1, input2);
48. }
Copy
  • define

Simply replace the identifier in the program . Macro parameters... Are not supported , as well as ## The connector and # operator .

1. #define NAME expression

3、 ... and 、 data type

1. Basic types

Frutta In language , Any operation is expressed as an integer operation , therefore Frutta There are several basic types of languages :

type digit Range of values
bool 8 The value is 0 and 1
int8 8 -128 ~ 127
uint8 8 0 ~ 255
int16 16 -32768 ~ 32767
uint16 16 0 ~ 65535
int32 32 -2147483648 ~ 2147483647
uint32 32 0 ~ 4294967295
int64 64 -9223372036854775808 ~ 9223372036854775807
uint64 64 0 ~ 18446744073709551615

You can also define custom types for different bytes .

1. typedef signed bytelength type;
2. typedef unsigned bytelength utype;
Copy

2. Implicit conversion of data types

Frutta Implicit conversions are performed in the following four cases :

a. In arithmetic expressions , Low type can be converted to high type .

b. In the assignment expression , The value of the right expression is implicitly converted to the type of the left variable , And assign it to him .

c. When passing parameters in a function call , After the system implicitly converts an argument to the type of a parameter , To a formal parameter .

d. When the function has a return value , The system implicitly converts the return expression type to the return value type , Assign to calling function .

When different types of data operate , It should first be converted to the same data type , And then operate , The conversion rule is from low level to high level .

 The conversion rules are as follows :
Copy

int8->uint8->int16->uint16->int32->uint32->int64->uint64.

To take one int8 -> uint8 Example :

1. int8 a = -41;
2. int8 b = -90;
3. uint8 c = a + b;
4. // The final result is 125
Copy

3. Structure (struct)

Frutta Support class C Linguistic Struct, To define the structure . Structs allow you to define variables that can store different types of data items .

1) Defining structure

1. typedef struct Point
2. {
3. int32 x;
4. int32 y;
5. }
6.
7. typedef struct Circle
8. {
9. Point p;
10. uint32 radius;
11. }
Copy

The above definition can be used Point,Circle Define structure variables .

2) Access structure members

To access members of the structure , We use the member access operator (.). Member access operator is an English period between the name of a structural variable and the structural member we want to access . Like defining a variable Circle c Access its member variables x It needs to be like this c.p.x.

4. Array

Frutta The language supports array data structure , It can store a fixed size sequential collection of elements of the same type . Array is used to store a series of data , But it's often thought of as a series of variables of the same type .

1) Declaration array

stay Frutta To declare an array , You need to specify the type of element and the number of elements , As shown below :type arrayName [ arraySize ]

Frutta Support multidimensional array , As shown below :type arrayName [row][col];

2) Initialize array

stay Frutta in , You can initialize arrays one by one , You can also use an initialization statement , As shown below :type balance[5] = {0, 0, 0, 0, 0};

Curly braces { } The number of values between can't be greater than what we have in brackets when we declare an array [ ] The number of elements specified in .

3) Accessing array elements

Array elements can be accessed by array name plus index . The index of the element is in square brackets , Following the array name . for example : type salary = balance[9];

The above statement will put the 10 The value of an element is assigned to salary Variable .

 

Four 、 Constant

Frutta in , There are integer constants and bool Constant .

  • bool Constant : stay Frutta in , Built in two bool Constant true and false, Binary respectively represents 00000001 and 00000000. Such as :
bool flag = true.
Copy
  • integer constants : Integer constants can be used 10 Into the system and 16 Hexadecimal said .16 Base needs to be 0x start . Such as :
uint32 YEAR = 365.

5、 ... and 、 Variable

Frutta in , Variables are just a lot of things that a program can do Wire The combination of .Frutta Each variable in has a different number of Wire, Operators can be applied to variables .

The name of the variable can be made up of the letters 、 Number and underscore characters . It must start with a letter or underscore . Capital letters and lowercase letters are different .

The variable definition specifies a data type ( The data type must be declared in the type definition ), And contains a list of one or more variables of this type , Such as :

type variable_list;
Copy

Variables can be initialized at the time of declaration ( Specify an initial value ). The initializer consists of an equal sign , Followed by a constant expression , As shown below :

type variable_name = value;

 

6、 ... and 、 Operator

An operator is a symbol that tells the compiler to perform a specific mathematical or logical operation .Frutta The language has built-in rich operators , The following types of operators are provided :

1. Arithmetic operator

Operator describe
+ Add the two operands
- Subtract the second operand from the first operand
* Multiply the two operands
/ Divide the numerator by the denominator
% Modulo operators , The remainder after division

2. Relational operator

Operator describe
== Check that the values of the two operands are equal , If they are equal then the condition is true .
!= Check that the values of the two operands are equal , If they are not equal then the condition is true
> Check whether the value of the left operand is greater than the value of the right operand , If so, the condition is true .
< Check whether the value of the left operand is less than the value of the right operand , If so, the condition is true .
>= Check whether the value of the left operand is greater than or equal to the value of the right operand , If so, the condition is true .
<= Check whether the value of the left operand is less than or equal to the value of the right operand , If so, the condition is true .

3. An operator

Operator describe
& If it exists in both operands , Binary system AND Operator to copy a bit into the result .
\ If it exists in any operand , Binary system OR Operator to copy a bit into the result .
^ If it exists in one of the operands but not both operands , Binary exclusive or operator copies a bit into the result .
<< Binary left shift operator . The value of the left operand moves left by the number of bits specified by the right operand .
>> Binary right shift operator . The value of the left operand moves right the number of bits specified by the right operand .

4. Assignment operator

Operator describe
= Simple assignment operators , Assign the value of the right operand to the left operand

 

7、 ... and 、 The operator

1. Take the line according to the position

Lines that support bitwise variables

Support with VAR{start:length} Method to get a variable from start At the beginning length Root line , Return value can be assigned

Give a variable , You can also directly participate in the calculation .

1. #parties 2
2. #input 1 int32
3. #input 2 int32
4. #output 1 int32
5.
6. function void main()
7. {
8. output1 = input1{0:8} + input2{0:8};// The number above is from 0 Start , take 8 individual bit Carry out operations
9. }

8、 ... and 、 Control statement

1. Conditional statements

Judgment structures require programmers to specify one or more conditions to evaluate or test , And the statement to execute when the condition is true ( Essential ) And the statement to execute when the condition is false ( Optional ).

sentence describe
if sentence One if sentence Consists of a Boolean expression followed by one or more statements .
if...else sentence One if sentence You can follow with an optional else sentence ,else Statement is executed when the Boolean expression is false .
nesting if sentence Can be in a if or else if Use another if or else if sentence .

2. Circular judgment statement

A loop statement allows us to execute a statement or group of statements more than once ,Frutta Only support for Loop statement , As shown below :

1. for(type i=0; i<max; i++)
2. {
3.
4. }
Copy

Be careful :

  • I won't support it break,continue sentence

  • The end condition i<max Must not depend on input Value , Must be a clear value

  • External type declarations such as are not supported for(; i<max; i++){ }

Nine 、 function

1. Function definition

A function is a set of statements that perform a task together . Every Frutta Every program has at least one function , The main function main() , All simple programs can define additional functions .

Frutta The function of is defined as follows :

1. function return_type foo(paramtype1 name1, paramtype2 name2, paramtype3[5] name3)
2. {
3. return blah;
4. }
5.
6. // An example is as follows
7. function int32 add(int32 x, int32 y)
8. {
9. return x + y;
10. }
11. // call
12. output1 = add(input1, input2);
Copy

All the components of a function :

  • Return type : A function can return a value .return_type Is the data type of the value returned by the function . Some functions perform the required operations without returning values , under these circumstances ,return_type Is the key word void.

  • The name of the function : This is the actual name of the function . Function name and parameter list together constitute function signature .

  • Parameters : Parameters are like placeholders . When a function is called , You pass a value... To the parameter , This value is called the actual parameter . The parameter list includes the types of function parameters 、 The order 、 Number . Parameters are optional , in other words , Function may not contain arguments .

  • Function main body : The function body contains a set of statements that define the function's execution tasks .

2. Built in functions

stay Frutta in , Built in the following functions :

function Function definition Function description
abs intxxx abs(intxxx) Take the absolute value , Input and output are signed integers . as follows :int32 y = abs(x)
min (u)intxxx min((u)intxxx, (u)intxxx) Take the minimum of two numbers , Input can be signed and unsigned integers , If there is a sign and no sign at the same time , If there is a sign, it will be automatically converted to no sign , Return value is null . as follows :int16 min(x, y)
max (u)intxxx max((u)intxxx, (u)intxxx) Take the maximum of two numbers , Input can be signed and unsigned integers , If there is a sign and no sign at the same time , If there is a sign, it will be automatically converted to no sign , Return value is null . as follows :int16 max (x, y)

 

Chapter four JUGO-IDE

1. What is? JUGO-IDE

JUGO-IDE yes JUGO Technical products are provided for developers to write MPC Algorithm development tools , combination Frutta Google browser plugin , Developers can write quickly without building any environment 、 compile 、 Running and publishing algorithms .

By using JUGO-IDE, Developers can use Frutta Language programming algorithm , And pass JUGO-IDE It can be compiled in JUGO Circuit files and... Executed on technical products java Template file .https://jugo.juzix.net/ide/

2. Support language

Frutta Language .

Frutta As a class C High level language , You can write the calculation logic in JUGO-IDE Generate circuit files and java Template file , And in JUGO Perform calculations in technical products . details

3 development environment

operating system windows( Follow up support linux),chrome browser ( It needs to be installed first Frutta Google browser plugin )

..

First step , Please click download Frutta Google browser plug-in installation package , And decompress it locally .

The second step , stay Chrome Browser address bar input chrome://extensions/, Enable Developer mode , Then click the button “ Load the unzipped extender ”, Select the folder where the plug-in is located .

Be careful : Because the plug-in has not been uploaded yet Google Plug in store , So it can only run in developer mode . open chrome://extensions/, Open the developer mode as shown below . Because it runs the plug-in in developer mode ,Chrome The browser will pop up “ Please disable the extensions running in developer mode ” A hint of , Click here “ Cancel ” To continue to use Frutta Google browser plugin . 

 

One 、 Interface

1. Startup page

1)JUGO-IDE The startup page contains a welcome page and an algorithm project by default , Developers can add and delete as needed .

2) Developer is not logged in JUGO For the first time in the case of technical products JUGO-IDE When starting the page , The login pop-up window will pop up automatically , Provides login 、 Forget the password 、 Registration and other functions . Developers can only use... After logging in JUGO-IDE Access algorithm library provided 、 The function of publishing algorithm . Of course , Developers can also click “ Don't log in ” Close the login pop-up window to continue using MPC-IDE, It will not affect functions such as project compilation .

3)JUGO-IDE Startup time , The edit area opens by default JUGO-IDE The welcome page , This page provides JUGO-IDE、Frutta、JUGO Technical products 、MPC Brief introduction and details page links , Developers can click “ details ” Go to the details page to learn more about .

1) file management

Function description : Provide “ New project 、 New file 、 Import local file 、 Export to local 、 Save the current file 、 Save all files 、 Delete current file ” And so on .

The operation sample :

  • New project : Click on the head “ Toolbar file -- New project ”, Can create algorithm engineering pop-up window , After the developer enters the algorithm name , That is, create a new algorithm project in the current file manager .

  • Algorithmic engineering directory structure :

  • libraries: The referenced algorithm stores the directory ;

  • bin: The current algorithm project is compiled successfully java Directory where template files are stored ;

  • Include: Algorithm Project header file storage directory ;

  • Resource: Algorithm engineering source file storage directory ;

  • main.wir: Current algorithm project entry file

Be careful : The compilation entry file of the current algorithm project is “main.wir”. If you select other files, click compile ,JUGO-IDE It will automatically locate the algorithm project of the currently selected file , And compile the “main.wir”. If you need to compile other files , Need to be in “main.wir” After importing the file, click “ compile ”.

  • New file : Click on the head “ Toolbar file -- New file ”, That is, create a new project in the current project directory Untitled1.wir file , And automatically open... In the editing area .

Functional limitation :IDE There is at least one project in the current file system .

  • Import local file : Click on the head toolbar “ file -- Import local file ”, Select a file and it will be imported into JUGO-IDE File manager , And automatically open... In the editing area .

Functional limitation :IDE There is at least one project in the current file system .

  • Export to local : Click on the head toolbar “ file -- Export to local ”, Will IDE The currently selected file or folder in is exported to local , The format of the folder is “ Folder name ”.rar, The format of the file and the currently selected file are in IDE The format in is consistent .

Functional limitation : Need to be in IDE Select a file or folder .

  • preservation / Save all : Click on the head toolbar “ file -- preservation ”, The current file will be saved ; Click on the head toolbar “ file -- Save all ”, All files in the file manager... Are saved ;

Functional limitation : There are files to save in the current window

  • Delete : Click on the head toolbar “ file -- Delete ”, The file opened in the window of the current editing area will be deleted ;

Functional limitation : There are currently selected files

2) Edit operation

Function description : Provide for current files “ revoke 、 recovery 、 Copy 、 shear 、 Paste 、 lookup 、 Replace 、 grid Formalization 、 Find in file 、 Replace... In the file ” And so on .

The operation sample :

Find in file / Replace : Click on the head toolbar “ edit -- Find in file / Replace ”, A search window will pop up in the left sidebar , Realize the search of global keywords / Replacement function .

Functional limitation : There are open files in the current editing area window

3) help

Function description : Provide help documentation for the operator .

The operation sample :

  • Welcome to use : Click on the head toolbar “ help -- Welcome to use ”, I will go back to JIDE Welcome page of , This page provides JIDE Brief introduction and general process of use .

  • Help document : Click on the head toolbar “ help -- Help document ”, It will jump to JUGO Documentation Center for technical products , The document center contains a more detailed development process . 

3. The toolbar

1) file management

Function description : Controls the expansion or collapse of the filer .

Operation steps : The file manager window expands by default , Click on the left toolbar “ file management  ” Controls the expansion and collapse of the file manager window

2) Global search

Function description : Provide global search 、 Replacement function .

Operation steps :

First step : Click on the left toolbar “ Search for  ” Button , Call up the global search function window ;

The second step : Enter keywords to instantly show search results , Keywords support case sensitive 、 Match whole words 、 Regular expressions ;

The third step : Click search results to automatically jump to the current file ;

Step four : Replacement operation supports single replacement and full replacement , After entering the replacement , You can choose between a single replacement and a full replacement ;

3) Run algorithm

Function description : Test and run the compiled circuit file .

Operation steps :

First step : Click on the left toolbar “ function  ” Button , Call up the run algorithm panel ;

The second step : If the currently selected project is not compiled successfully , There is no data ;

The third step : If the currently selected project has been compiled successfully , Then you can enter the input to run the algorithm ;

Step four : The successful running , In the output field, you will be prompted that the operation is successful and enter the operation result ;

Step five : After successful operation , You can see the running result , The format is as follows “name:value”,”name” That is, the name of the output variable in the currently running algorithm code ,”value” Output the value of the variable in the algorithm code .

4) Algorithm library

Function description : All algorithms that have been uploaded to the algorithm Center , Can be invoked in algorithm library , Click the icon to enter the algorithm library page .

Operation steps :

Be careful : Entering the algorithm library requires that the user has logged in , If you are not logged in, you need to log in .

First step : Click on the left toolbar “ Algorithm library  ” Button , Call up the algorithm library panel ; The algorithm list shows the name of each algorithm 、 Profile and publisher , Support keyword search algorithm ;

The second step : Click on an algorithm , Skip to the details interface of the algorithm , Developers can learn more about the algorithm , It also provides a function entry for downloading the algorithm .

Functional limitation : Developers need to log in to access , If the developer is not logged in ,IDE The login pop-up window will pop up automatically to prompt developers to log in .

3. Editing area

1) Syntax check

Function description : Execute... On the currently edited file “ preservation ” perhaps “ compile ” Operation of , Grammar check , The wrong place is marked with a red cross , Hovering the mouse over the line of text will display specific error messages .

2) lookup / Replace

Function description : Enter keywords to search / Replace , Support case sensitive 、 Match whole words 、 Regular expressions . Search results support the last 、 Next positioning operation , The replacement operation supports single replacement and the replacement operation of all files in the current editing area .

3) Multiple windows show

Function description : When too many files are opened in the editing area , Some of the hidden files can be on the right “ More documents ” The entrance opens .

Operation steps : Click more files on the right “...” identification , You can call up the file list , Among them, the file shown in black is the file already displayed in the editing area , Gray shows hidden files ;

4) Right click in the window

Function description : Provide “ close 、 Turn off other 、 Close the right side 、 Close unchanged 、 Close all ” function .

Operation steps : Select a file name , Right click to call up the right-click operation menu .

5) Document status identification

Function description : A small red dot icon appears to the left of each file name , It means that the file has not been saved after the change ; The little green dot icon appears , It means that the file has been saved .

Two 、 Shortcut key

Key name operation Functional limitation
Alt+p New project nothing
Alt+N New file IDE There is at least one project in the current file system
Ctrl+O Import local file IDE There is at least one project in the current file system
Ctrl+S preservation IDE There are unsaved files in the current file system
Ctrl+Alt+S Save all IDE There are unsaved files in the current file system
Ctrl+delete Delete There are currently selected files
Ctrl+Z revoke There are open files in the current editing area window
Ctrl+Y recovery There are open files in the current editing area window
Ctrl+C Copy There are open files in the current editing area window
Ctrl+X shear There are open files in the current editing area window
Ctrl+V Paste There are open files in the current editing area window
Ctrl+F lookup There are open files in the current editing area window
Ctrl+H Replace There are open files in the current editing area window
Ctrl+L Code formatting There are open files in the current editing area window
F2 rename There are currently selected files
F8 compile IDE There is at least one project in the current file system

3、 ... and 、 Writing process

1. File format

1) Input file format

JUGO-IDE Currently, it supports editing of all format files , But compilation is limited to .wir File format .

2) Output file format

stay JUGO-IDE One to one .wir Compiling a file in this format will generate a .gc Format the circuit file and a .java Format java Template file ;.gc Documents are available through “ export ” Button export to local ,.java Documents are placed on the project “bin” Catalog , From the menu bar or toolbar “ Export to local ” Function export to local ,.java Documents can be found in java-sdk Use in ..

2. Automatic completion

Function description :JUGO-IDE The editing area will display the prompt of automatic completion in the process of input .

3. Programming

Function description :JUGO-IDE Edit area provides search 、 Replace 、 Code formatting 、 Enlarge the font 、 Font reduction 、 revoke 、 Common functions such as recovery .

technological process : edit -- preservation -- compile

Wrong type feedback :

1) When a developer performs a save operation , If there is a syntax error in the code , There is a red cross at the wrong line number , Hovering the mouse over the line of text will display specific error messages .

2) When a developer performs a compilation operation , If there is a compilation error ,IDE The output area will have a red error message output , Click on the error message , The editing area will automatically open the file with the current error .

measures : If the developer has an error message when saving or compiling , You need to edit the file again to correct errors before saving or compiling .

4. function

Function description :JUGO-IDE The editorial area provides “ lookup 、 Replace 、 Code formatting 、 Enlarge the font 、 Font reduction 、 revoke 、 recovery ” Common functions such as .

technological process : The current project is compiled successfully and then executed

Wrong type feedback :

1) The current project did not compile successfully

measures : Developers need to compile the current project first , Only after the compilation is successful can the algorithm run .

2) Invalid parameter

measures : When the current project is compiled and run successfully , The input parameters will be type and range verified , Cannot click... When there are illegal parameters “ function ” Button .

5. Release

Functional limitation :

1) Developers need to log in .

2) The current project compiles successfully and passes the run test .

purpose : Developers can publish the algorithm that has passed the running test to JUGO Algorithm library of technical products , The algorithm library is JUGO Algorithm warehouse of technical products , Developers use JUGO-IDE The published algorithm will generate a unique algorithm ID, Through this algorithm ID You can download the algorithm , And pass JUGO-SDK Use this algorithm . details

6. Algorithm library

Functional limitation : Developers need to log in .

purpose : Developers can access JUGO All algorithms in the algorithm center of technology products . The algorithm list shows the name of each algorithm 、 Profile and publisher , Support keyword search algorithm ; Click on an algorithm , Skip to the details interface of the algorithm , Developers can learn more about the algorithm , It also provides a function entry for downloading the algorithm .

7. export

Function description : Developers can export functions to JUGO-IDE The currently selected file or folder in is exported to local , The format of the folder is “ Folder name ”.rar, The format of the file and the currently selected file are in IDE The format in is consistent .

 

Four 、 Sign in

Developers log in to access JUGO-IDE Access algorithm library provided 、 The function of publishing algorithm .

The fifth chapter 、JUGO-SDK

1. summary

SDK(SoftwareDevelopmentKit) It is usually a collection of development tools for developing application software . and JUGO-SDK It is a development kit for secure multiparty computing applications . adopt JUGO-SDK, Developers can develop efficiently MPC( secure multi-party computation ) application .

JUGO-SDK It provides rich application development interfaces , But also MPC Of computing nodes —— adopt SDK Call to , Applications can upload data 、 Algorithm call 、 Calculate invitations 、 Task acceptance 、MPC Local computing and other functions . Make the data without leaving the local , Get calculation results .

The purpose of this document is to introduce JUGO-SDK Use and precautions .

2. programing language & development environment

Support language :   JAVA Language
JDK edition : JDK1.8
development tool :   Recommended IntelliJ IDEA
development environment :   operating system window/linux,ICE-3.6
Debug environment :   The algorithm library only supports .so Dynamic library (Linux Platform operation ), The complete calculation process needs to be in Linux On the environment , Some of the development functions can be found in window Debug on .
Running environment :   Currently, only running in Linux Environmental Science , recommend :CentOS Linux release 7.2.1511 (Core)
Circuit files :   The suffix format is specified as :.gc
            other :            JUGO-SDK Used Ice Medium Glacier2 Firewall penetration , Readers need to have distributed system middleware (Ice) Basic knowledge of

One 、JUGO-SDK Use steps

This chapter mainly introduces JUGO-SDK The use of footstep

1. introduce JUGO-SDK

SDK Warehouse address http://sdk.juzix.net/content/groups/public/

Maven

1. <dependency>
2. <groupId>com.juzix.jugo</groupId>
3. <artifactId>mpc-node-sdk</artifactId>
4. <version>1.3.0</version>
5. </dependency>
Copy

Gradle

1. compile "com.juzix.jugo:mpc-node-sdk:1.3.0"
Copy

Jar Package reference download

After downloading, you will get a zip package , After unpacking, it will correspond to jar All packages are copied to the local project and depend on references .

2. Configure algorithm dynamic library

Use of underlying algorithm logic c/c++ Compiling ,JAVA Use JNI To call . At present, only Linux Dynamic library in environment (.so), So the test should be done in Linux complete . Download and unzip to get a libjuzixmpc.so,libjuzixMpcSDK.so Dynamic library files , The configuration file needs to be changed mpc-node-config.conf To configure .

notes : This operation must be completed , Otherwise, the calculation operation cannot be completed .

Algorithm dynamic library   download

3. Profile creation

The calculation task is in the process of execution , When you need to get the configuration information of the circuit file ,JUGO-SDK Will use the default way to get , The default is to archive in classespath route ; Such as custom implementation CircuitManager, There is no need to provide a profile . It is stipulated here that , The profile name is :mpc-node-config.conf, Must be in the directory config Next . The configuration file can be located at classes Source directory or ${user.dir} working directory . If you use IDEA development tool , The configuration file can be placed in :${project.dir}/src/main/resources/config/mpc-node-config.conf.

The contents of the document are as follows :

1. node {
2. isDebug=false
3. # Whether to use Glacier2 Routing messages false Don't use , true Use
4. isRouterModel=false
5. circuit {
6. # Download address of circuit file , Here will be IP and port Change to the actual address
7. download.url = "http://xxx:port/file_api/file/download?arithmeticId=%s&user=%s"
8. # Circuit file local storage directory
9. local.dirPath = /home/test/developer/jugompc
10. }
11. jni {
12. # jni Call the dynamic library file directory
13. library.path=/home/test/developer/jnilib
14. }
15. }
Copy

notes : Complete the above 2 Step operation is basically completed JUGO-SDK Integration of . Please note that the file path of algorithm library is configured correctly .

4. Configure the node as a service node

On node startup , Divided into service node startup , And non service node startup .

The service node is , Only task requests are transmitted through the proxy service callback , The rest of the process interacts directly with the opposite node . Calling API- Initialize node (initContext) when , If parameters mode Pass in SERVER, The configuration operation must be performed .

The non service node is , The task request and the intermediate computing communication are transmitted through the proxy server callback .

When the node needs to be started as a service node , Need to provide service profile , And in the initialization through the parameters args Pass in .

1) Service profile :config.node-server

1. # The current node is provided as a service Endpoints Information
2. NodeServer.Endpoints=tcp -h 0.0.0.0 -p 12001
3. NodeServer.Nodepoint=tcp -h47.100.43.6 -p 12001
4. Ice.ThreadPool.Server.Size=4
5. Ice.ThreadPool.Server.SizeMax=4
6. Ice.ThreadPool.Client.Size=1
7. Ice.ThreadPool.Client.SizeMax=1
8.
9. #tcp keepalive
10. Ice.ACM.Close=4 # CloseOnIdleForceful
11. Ice.ACM.Heartbeat=0 # HeartbeatOff
12. #Ice.ACM.Heartbeat=3
13. Ice.ACM.Timeout=10
Copy

notes : In creating a circuit instance

args=new String[]{“--Ice.Config=config.node-server”}
Copy

2) Computation cannot be performed between a service node and a non service node .

Two 、API Interface

API explain
YourCircuitWrapper() Initialization context , Building circuit objects
doCompute() Start the calculation task
setInputCallbackForORG() Set the initiator calculation data source callback CALLBACK
setInputCallbackForDST() Set the invited party to calculate the data source callback CALLBACK
setOutputCallbackORG() Set the initiator result processing callback CALLBACK
setOutputCallbackDST() Set the callback of invited party result processing CALLBACK
invite() Whether to accept the calculation invitation
getLocal() Get circuit file path
setDataLogLevel() Controls whether calculated data is output to a file , And according to the level of printing output .

Here are API Detailed introduction of the interface .

1. Create a circuit instance

Interface :YourCircuitWrapper circuit=new YourCircuitWrapper();

Be careful : Circuit file packaging class , Instantiate only once , Establish a connection with the agent .

describe : Create a circuit instance , And complete the link initialization , And JUGO Proxy service for session connection , Subsequent data communication depends on this connection channel .

Parameter description :

Parameters type Required explain
pcbId String    yes    circuit ID, Generally the same as the circuit file name , This value will be used for local circuit file search . Such as :xxx.gc
user String    yes    Node user name , Used to connect to JUGO Platform agent service for authentication . Get it from JUGO The development service platform is registered
password String    yes    The user name corresponds to the password , Used to connect to JUGO Proxy service session connection authentication . This password corresponds to JUGO The password corresponding to the registered account of the development service platform
mode NodeCommunicateMode    yes    Node start mode , There are two types of SERVER - After node initialization, it starts as a service node at the same time CALLBACK - After node initialization, start as a callback node. Please refer to JUGO-SDK Use the procedure section
proxyEndpoint String    yes    JUGO Agent service Endpoints Connection information . for example :ProxyGlacier2/router:tcp -h 192.168.7.167 -p 4502 -t 11000
jugoEndpoint String    no    Current node Endpoint Information , When mode == SERVER when , This value is required .mode == CALLBACK You don't need to fill in
args Array    yes    Start configuration information . Such as : Carry the node service configuration information :--Ice.Config=config.conf

Return parameter description :

Parameters explain
No return parameter You need to handle the exceptions that may be triggered during the call MPCException

Sample code :

1. try {
2. YourCircuitWrapper yourCircuit=new YourCircuitWrapper("mycircuitId","admin01","password",NodeCommunicateMode.SERVICE
3. , "ProxyGlacier2/router:tcp -h 192.168.7.167 -p 4502 -t 11000", null, "--Ice.Config=config.conf");
4. } catch (MPCException e) {
5.
6. }
Copy

2. Start calculation task

Interface :yourCircuit.doCompute();

Be careful : Make sure you have successfully built YourCircuitWrapper Instance object .

describe : By calling doCompute, You can start a calculation task . This interface is called by the task initiator , The invited party does not need to call the interface .

Parameter description :

Parameters type Required explain
roomId String    yes    Calculation example ID, The value is determined by JUGO Development service platform provides , This value is generated when a calculation task is created
args Array    no    Calculation conditions , Parameters can be extended at will , However, it is necessary to ensure that all calculation participants have the same parsing process for this field . Such as : Pass it here A=15 B=15 C=17, After receiving the data, other participants analyze the parameter structure according to the rules to obtain
takerList List    yes    Calculate party user name list , The first element in the list is the calculation task initiator
resultReceiverList List    yes    Calculation result receiver list , After the calculation, all users in the list will receive the calculation results

Return parameter description :

Parameters explain
No return parameter You need to handle the exceptions that may be triggered during the call MPCException

Sample code :

1. try {
2. String[] argsAttach = new String[]{"n=3","m=4"};
3. List<String> takerList = Arrays.asList(new String[]{"admin01","admin02"});
4. List<String> resulReceiverList = Arrays.asList(new String[]{"admin01"});
5. yourCircuit.doCompute("1111", argsAttach, takerList, resulReceiverList);
6. } catch (MPCException e) {
7. e.printStackTrace();
8. }
Copy

3. Initiator obtains source data

Interface :yourCircuit.setInputCallbackForORG();

Be careful : This function is used to set the source data acquisition method of the calculation initiator .

describe : This function accepts a InputCallback() The concrete implementation of the interface , You can define the acquisition logic of the calculation source data . Please pay attention to the data structure specification defined in the circuit file when setting , If it is an array, you need to ensure that the number of elements and element levels are consistent with the predefined .

Parameter description :

Parameters type Required explain
taskId String    yes    Mission ID, Callback incoming . Every time a calculation is initiated, a new task is created ID
algorithmId String    yes    Algorithm ID, Callback incoming . Each task corresponds to an algorithm ID
args Array    yes    Additional parameters , This parameter is calling startTask When it came in args Parameters , You can use this parameter to carry conditions ( If the business needs ), The parameters received by any participant are consistent

Return parameter description :

type explain
Return specific type defined by circuit file nothing

Sample code :

1. yourCircuit.setInputCallbackForORG(new InputCallback<Int32[][]>() {
2. @Override
3. public Int32[][] input(String taskId, String algorithmId, String[] args) {
4. return new Int32[2][2];
5. }
6.
7. @Override
8. public void onFailure(Throwable e, String[] args){
9. // exception handling
10. }
11. });
Copy

explain :

The generated circuit is assumed in the above example java The type of input parameter defined in the file is :Int32[][], One Int32 Two dimensional array of , And the number of elements is [2][2].

4. Invitees get source data

Interface :yourCircuit.setInputCallbackForDST();

Be careful : This function is used to set the source data acquisition method of the invited initiator .

describe : This function accepts a InputCallback() The concrete implementation of the interface , You can define the acquisition logic of the calculation source data . Please pay attention to the data structure specification defined in the circuit file when setting , If it is an array, you need to ensure that the number of elements and element levels are consistent with the predefined .

Parameter description :

Parameters type Required explain
taskId String    yes    Mission ID, Callback incoming . Every time a calculation is initiated, a new task is created ID
algorithmId String    yes    Algorithm ID, Callback incoming . Each task corresponds to an algorithm ID
args Array    yes    Additional parameters , This parameter is calling startTask When it came in args Parameters , You can use this parameter to carry conditions ( If the business needs ), The parameters received by any participant are consistent

Return parameter description :

type explain
Return specific type defined by circuit file nothing

Sample code :

1. yourCircuit.setInputCallbackForDST(new InputCallback<Int32[][]>() {
2. @Override
3. public Int32[][] input(String taskId, String algorithmId, String[] args) {
4. return new Int32[3][3];
5. }
6.
7. @Override
8. public void onFailure(Throwable e, String[] args){
9. // exception handling
10. }
11. });
Copy

explain :

The generated circuit is assumed in the above example java The type of input parameter defined in the file is :Int32[][], One Int32 Two dimensional array of , And the number of elements is [3][3]. So in the callback function input The return of must be [3][3] And .

5. Set the initiator result processing callback

Interface :yourCircuit.setOutputCallbackForORG();

Be careful :N/A.

describe : Set up a callback function , Used to process the results obtained . The data type returned by the result is the same as that of the circuit file algorithm circuit .

Parameter description :

Parameters type Required explain
taskId String    yes    Mission ID, Callback incoming . Every time a calculation is initiated, a new task is created ID
algorithmId String    yes    Algorithm ID, Callback incoming . Each task corresponds to an algorithm ID
resultCode int    yes    Result error code ,0 Indicates successful data acquisition .
result <T>    yes    The result of the calculation is , Its type depends on the circuit , It's dynamic . May be :Int32/Int64/Int32[]/Int32[][]
args String[]    yes    Calculation conditions , By the sponsor , All parties will receive this parameter .
type MPCTaskType    yes    Task type :ALICE(0),BOB(1), Enumeration value is used to identify the current task type as initiator (ALICE) Or the invited party (BOB).

Return parameter description

type explain
void No return value

Sample code :

1. yourCirciut.setOutputCallback(new OutputCallback<Int32>(Int32.class) {
2. @Override
3. public void onResult(String taskId, String algorithmId, int resultCode, Int33 result, String[] args, MPCTaskType type) {
4. // Processing results
5. }
6.
7. @Override
8. public void onFailure(Throwable e, String[] args){
9. // exception handling
10. }
11. }
Copy

Be careful : The data type in the example (Int32) Determined by specific circuit documents .

6. Set the callback of invited party result processing

Interface :yourCircuit.setOutputCallbackForDST();

Be careful :N/A.

describe : Set up a callback function , Used to process the results obtained . The data type returned by the result is the same as that of the circuit file algorithm circuit .

Parameter description :

Parameters type Required explain
taskId String    yes    Mission ID, Callback incoming . Every time a calculation is initiated, a new task is created ID
algorithmId String    yes    Algorithm ID, Callback incoming . Each task corresponds to an algorithm ID
resultCode int    yes    Result error code ,0 Indicates successful data acquisition .
result <T>    yes    The result of the calculation is , Its type depends on the circuit , It's dynamic . May be :Int32/Int64/Int32[]/Int32[][]
args String[]    yes    Calculation conditions , By the sponsor , All parties will receive this parameter .
type MPCTaskType    yes    Task type :ALICE(0),BOB(1), Enumeration value is used to identify the current task type as initiator (ALICE) Or the invited party (BOB).

Return parameter description

type explain
void No return value

Sample code :

1. yourCirciut.setOutputCallback(new OutputCallback<Int32>(Int32.class) {
2. @Override
3. public void onResult(String taskId, String algorithmId, int resultCode, Int33 result, String[] args, MPCTaskType type) {
4. // Processing results
5. }
6.
7. @Override
8. public void onFailure(Throwable e, String[] args){
9. // exception handling
10. }
11. }
Copy

Be careful : The data type in the example (Int32) Determined by specific circuit documents .

7. Deal with the result of the invitation

Interface :InvitationManager->invite();

Be careful : This interface provides a default implementation , If you need to change it, you need to call doCompute() Reset before . Callable yourCircuit.setInvitationManager(); Make changes .

describe : An interface , And provide callback function , When the node receives the calculation invitation, the callback will be triggered , Business logic can be provided in the callback function to decide whether to agree to calculate the invitation . This interface provides a default implementation class (DefaultInvitationManager)

Parameter description :

Parameters type Required explain
taskId String    yes    Mission ID, Callback incoming . Every time a calculation is initiated, a new task is created ID
starter String    yes    Calculate initiator user name
algorithmId String    yes    Algorithm ID, Callback incoming . Every task has an algorithm ID
numberOfParticipants int    yes    Number of participants
takersList List<String>    yes    Calculate party user name list

Return parameter description :

type explain
boolean Calculate the result of invitation confirmation ,true Agree to participate in the calculation ,false Refuse to participate in the calculation

Sample code :

1. yourCircuit.setInvitationManager(new InvitationManager() {
2. @Override
3. public boolean invite(String taskId, String starter, String algorithmId, int numberOfParticipants, List<String> takersList) {
4. // Business logic is implemented here
5. return true;
6. }
7. });
Copy

8. Get local circuit file

Interface :CircuitManager -> getLocal();

Be careful : If you need to change, call doCompute Reset before . Callable yourCircuit.setCircuitManagerManager(); Preset .

describe : This interface provides the default implementation class (DefaultCircuitManager). When you need to customize the circuit file path, you can provide the interface implementation again .JUGO-SDK Default will be based on Algorithm ID(algorithmId) Go to the circuit store to download ( from JUGO Development service platform provides ).

Parameter description :

Parameters type Required explain
algorithmId String    yes    Algorithm ID, Priority will be based on Algorithm ID Local search as filename ( suffix .gc), If not, it will be downloaded from the circuit file warehouse

Return parameter description :

type explain
String Return the full path of the circuit file stored locally

Sample code :

1. // Examples are provided according to different ID Return circuit files of different file types
2. yourCircuit.setCircuitManager(new CircuitManager() {
3. @Override
4. public String getLocal(String algorithmId) {
5. if(algorithmId.equals("1")){
6. return "/home/juzhen/work2018/jugo/jugompc/circuits-files/adder_32bit.gc";
7. }
8. if(algorithmId.equals("2")){
9. return "/home/juzhen/work2018/jugo/jugompc/circuits-files/AES-expanded.gc";
10. }
11. return "";
12. }
13. });
Copy

9. Set the log level

Interface :NodeContext->setDataLogLevel();

Be careful : If you need to change, call doCompute Reset before . Callable NodeContext.setDataLogLevel(); Preset .

describe : This interface is mainly used in scenarios where data in the calculation process needs to be recorded , Set the switch and specify the level to control the data during calculation .

Parameter description :

Parameters type Required explain
switch boolean    yes    Log switch , Whether the output :true Output data , Don't output data . The output log directory specifies how to add... To the array when initializing the circuit instance creation :--Mpc.Data=/opt/data
level int    yes    The level of logging :0 trace,1 debug,2 info, 3 warn,4 error

Return parameter description :

type explain
int Set result ,0 Mark success

Sample code :

1. // Example : Set the switch on , And set the level to 1(debug)
2. NodeContext.setDataLogLevel(true,1);

 

3、 ... and 、 List of return codes

Error code explain
0 Calculation successful
100 Program unknown exception
1001 The connection fails , The Internet is not working
1007 Participate in the calculation of node abnormal logoff
1008 There are nodes that refuse to participate in the calculation
1009 Circuit file missing

Chapter six 、 Classic case

1. Business logic

Millionaire classic question by Turing Award winner 、 Professor Yao Jizhi, academician of the Chinese Academy of Sciences, is in 1982 in . There are two millionaires in the question ——Alice and Bob, They want to know who is richer , But they don't want to let each other know any wealth information . The solution to this problem extends an important branch of cryptography —— secure multi-party computation (MPC:Secure Multi-Party Computation).

This case will restore the millionaire problem scene :

1) Either side of the calculation , Enter value in case application , And initiate calculations ;

2) The other party will fill in the number of the task invitation , Just go ahead MPC Calculation .

3) In the end, both parties will get the only calculation result : The initiator is richer than the receiver , Or the initiator is not richer than the receiver .

In the process , Both parties can't get the value of each other's value , It is also impossible to deduce the value of each other's value from the interactive data .

2. Usage algorithm

from JUGO IDE Compiled 32 Bit ratio size algorithm circuit file .

One 、 Code

JUGO A complete case application has been deployed in the open service platform , Direct access to .

Online address :https://jugo.juzix.net/demo/,

If you want to Experience the complete deployment process of the case and use it locally , Please refer to the following introduction :

Three parts of the code are integrated in the case . Include ,

1) Algorithm code .

2) Server application code .

3) The front page shows the code .

1. Algorithm code

1. #parties 2
2. #input 1 uint32
3. #input 2 uint32
4. #output 1 uint32
5. function void main()
6. {
7. /* Data comparison circuit (output1=1 && input1>input2)*/
8. output1 = input1/input2;
9. if(output1>0)
10. {
11. output1 = 1;
12. }
13. }
Copy

2. Server code

1) Initialize node

describe

introduce JUGO platform SDK library ;

Initialize node , Start node listening ( Including the initiator node and the receiver node );

JUGO The node initialization of is returned asynchronously .

Code reference :

 1. compare = new Compare(SystemProperties.getDefault().getCompare(), SystemProperties.getDefault().getNode1UserName(), SystemProperties.getDefault().getNode1Password(), mode,SystemProperties.getDefault().getNode1Endpoint(), null, argsAttach);
2. // Set the returned callback object , Processing results return data , For initiator use setOutputCallbackForORG. Use... For invitees setOutCallbackForDST
3. compare.setOutputCallback(new OutputCallback<Uint32>(Uint32.class){
4. @Override
5. public void onResult(String taskId, String algorithmId, int resultCode, Uint32 result,String[] args, MPCTaskType mpcTaskType) {
6. logger.debug(" Get results : Mission ID:{}, Algorithm ID:{}, Error code :{}, value :{}",
7. taskId, algorithmId, resultCode, result.getValue().toString());
8. // Judge the result according to the return value
9. if(resultCode == 0){
10. resultMapper.insertData(id, " Get the end result , Return data results : Our value is greater than or equal to the other party's value , Mission id:" + taskId, new Date(),Const.getType_one());}
11. else{
12. resultMapper.insertData(id, " Get the end result , Return data results : The other side is worth more , Mission id:" + taskId ,new Date(), Const.getType_one());}
13. }
14. @Override
15. public void onFailure(Throwable e,String[] args) {
16. e.printStackTrace();
17. }
18. });
19. // The inviting party defines the input parameters . Call... For the input initiator setInputCallbackForORG Method , Called by the invited party setInputCallbackForDST Method .
20. compare.setInputCallbackForORG(new InputCallback<Uint32>() {
21. @Override
22. public Uint32 onInput(String taskId, String algorithmId, String[] args) {
23. resultMapper.insertData(id, " Prepare to participate in the calculation of parameters , Initiate calculation , Mission id:" + taskId, new Date(),Const.getType_one());
24. // Initialize background input parameters
25. return new Uint32(BigInteger.valueOf(3));
26. }
27. @Override
28. public void onFailure(Throwable e,String[] args) {
29. e.printStackTrace();
30. }
31. });
Copy

2) Node start task

describe :

If it's the invited party , There is no need to start the task

If it's the sponsor , A launch task is required

JUGO The node initialization of is returned asynchronously

Code reference :

1. // Initialize both sides of the calculation
2. List<String> takerList = Arrays.asList(new String[] { "admin01", "admin02" });
3. // Initialize the party receiving the result
4. List<String> resulReceiverList = Arrays.asList(new String[] { "admin01" , "admin02"});
5. // Start node task
6. compare.doCompute(SystemProperties.getDefault().getRoomId(), argsAttach, takerList, resulReceiver

 

3、 ... and 、 Implementation process

1.MPC Application deployment

1) preparation

Environment building ( requirement linux System )

install nginx

install JDK, To configure JDK environment variable

2. Project package

1) describe :

Project dependence gradle Build ;

It can be done by gradle The instructions are packed , The file output is at the same level build Under the table of contents ;

It can be done by JAVA IDE Package executables ;

2)gradle Instructions :

1.>clean build
Copy

3. Configuration description and modification

1)jar Package sibling Directory /config/mpc-config/mpc-node-config.conf modify :

node {
isDebug=false
# Whether to use Glacier2 Routing messages false Don't use , true Use
isRouterModel=false
circuit {
# Download address of circuit file , Here will be IP and port Change to the actual address
download.url = "http://xxx:port/file_api/file/download?arithmeticId=%s&user=%s"
# Circuit file local storage directory Same as 2.4 route
local.dirPath = /home/mpc/gc
}
jni {
# jni Call the dynamic library file directory Same as 2.3 route
library.path=/home/mpc/jnilib
}
}
Copy

jar Configuration changes in package , With application.properties For example , route jar:// BOOT-INF\classes application.properties:

# Run service port port configuration
server.port=8082
server.session-timeout=60
server.tomcat.max-threads=0
server.tomcat.uri-encoding=UTF-8
server.context-path=/
#JDBC To configure . The corresponding url、username and password
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mpc?useUnicode=true&amp;charaterEncoding=utf-8
spring.datasource.username=mpc
spring.datasource.password=Juzhen123!
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
env=dev
# room id, You can fill it in at will
localRoomId=1
# The algorithm name , In the future, the corresponding algorithm will be queried according to the path
cirName=Compare
# User name of this node
node1Name=test002
# Invited user name ( Same user name of the other party )
node2Name=test001
# Node access password ( Not used temporarily , Feel free to type )
nodePassword=123456
# Node access address , take ip and prot Modify to actual use
nodeEndpoint=ProxyGlacier2/router:tcp -h 192.168.112.158 -p 4502 -t 11000
Copy

4. Project operation

1) describe :

Execute the following instructions in the environment to monitor ;

The statistical catalogue can be used later nohup.out Check the output log

2) Instruction reference :

1.>nohup java -jar MPCAcceptApp.jar &// Start the receiver node
Copy
2.>nohup java -jar MPCStartApp.jar &// Start initiator node
Copy

5. Project commissioning

Deployment complete

Enter... In the browser

http://ip:port/swagger-ui.html, Can debug initiator interface

Enter... In the browser

http://ip:port/swagger-ui.html, Debuggable receiver interface

6. Online version

https://jugo.juzix.net/demo/

Chapter vii. Website user manual

1. register

  • visit JUGO After opening the service platform , Click on the top right corner “ register ” Button , Go to the user registration page .

  • You can choose to register as an individual user or enterprise user , The difference between the two is shown in the figure above . Individual users can be upgraded to their users .

1.1. Personal user registration

  • register

Click on “ Become an individual user ”, Jump to personal user registration page .

Fill in the relevant information as required and click Register . The user name is required : user name 4-20 Characters , In English 、 Number and underline composition , Beginning of letter .

  • Generate and download certificates

After successful registration, you need to create an identity certificate , As the identity credentials to participate in secure multiparty computing . Click OK to generate the certificate file .

The initial password of the certificate is the same as the login password of the account you set , It is recommended that you back up to the local .

1.2. Enterprise user registration

  • register

On the registration page , Click on “ Become an enterprise user ”, Jump to the enterprise user registration page .

Three steps to register :

  1. Fill in the basic information ;

  2. Upload enterprise information ;

  3. Information Review .

Enterprise information needs JUGO After the open service platform administrator reviews , The user can use .

  • Generate and download certificates

Same as 1.1 Personal user registration —— Generate and download certificates

 

 

版权声明
本文为[Cross Chain Technology Practitioners]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple